Форум программистов, компьютерный форум, киберфорум
Java EE (J2EE)
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.50/4: Рейтинг темы: голосов - 4, средняя оценка - 4.50
1 / 1 / 0
Регистрация: 09.01.2019
Сообщений: 76

Как сделать правильно авторизацию

07.06.2019, 06:25. Показов 852. Ответов 2
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
Я хочу в своем проекте реализовать одну фукнцию. У меня есть список студентов, я хочу чтобы на ту jsp страницу мог заходить только авторизованный пользователь в моем случае только админ. Когда я запускаю проект он просит войти, когда я нажимаю войти он не запращивает логин и пароль и сразу же отправляет на странице где список студентов. А нужно чтобы он запросил логин и пароль и если он правильный то только тогда можно будет войти.

AuthorizationController
Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
package adil.java.schoolmaven.controller;
 
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
 
@Controller
public class  AuthorizationController{
 
    // If user will be successfully authenticated he/she will be taken to the login secure page.
    @RequestMapping(value="/admin", method = RequestMethod.GET)
    public ModelAndView adminPage() {
 
        ModelAndView m = new ModelAndView();
        m.addObject("title", "Вы успешно вошли");
        m.addObject("message", "Основная");
        m.setViewName("admin");
                
                return new ModelAndView("redirect: allStudents");
        
    }
 
    // Spring security will see this message.
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public ModelAndView login(@RequestParam(value = "error", required = false) String error, 
            @RequestParam(value = "logout", required = false) String logout) {
 
        ModelAndView m = new ModelAndView();
        if (error != null) {
            m.addObject("error", "Неверный логин и пароль");        
        }
 
        if (logout != null) {
            m.addObject("msg", "Вы успешно вышли");       
        }
 
        m.setViewName("login");
         
                 return new ModelAndView("redirect: allStudents");
    }
}
StudentController
Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
package adil.java.schoolmaven.controller;
 
import java.io.File;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletContext;
import adil.java.schoolmaven.entity.Student;
import adil.java.schoolmaven.service.StudentService;
import java.nio.file.FileSystemException;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
 
@Controller
public class StudentController {
 
    @Autowired
    private ServletContext servletContext;
 
    // Constructor based Dependency Injection
    private StudentService studentService;
 
    public StudentController() {
 
    }
 
    @Autowired
    public StudentController(StudentService studentService) {
        this.studentService = studentService;
    }
 
    
   
   
    @RequestMapping(value = "/allStudents", method = {RequestMethod.GET, RequestMethod.POST})
 
    public ModelAndView displayAllUser() {
        System.out.println("User Page Requested : All Students");
        ModelAndView mv = new ModelAndView();
        List<Student> studentList = studentService.getAllStudents();
        mv.addObject("studentList", studentList);
        mv.setViewName("allStudents");
        return mv;
    }
 
    @RequestMapping(value = "/addStudent", method = RequestMethod.GET)
    public ModelAndView displayNewUserForm() {
        ModelAndView mv = new ModelAndView("addStudent");
        mv.addObject("headerMessage", "Add Student Details");
        mv.addObject("student", new Student());
        return mv;
    }
 
    @PostMapping(value = "/addStudent")
    public String saveNewStudent(@RequestParam("name") @NonNull String name,
            @RequestParam("surname") @NonNull String surname,
            @RequestParam("avatar") MultipartFile file)
            throws IOException {
 
        Student student = new Student();
        student.setSurname(surname);
        student.setName(name);
 
        if (file != null && !file.isEmpty()) {
            student.setAvatar(studentService.saveAvatarImage(file).getName());
        }
 
        studentService.saveStudent(student);
        return "redirect:/allStudents";
    }
 
    @GetMapping(value = "/editStudent/{id}")
    public ModelAndView displayEditUserForm(@PathVariable Long id) {
        ModelAndView mv = new ModelAndView("editStudent");
        Student student = studentService.getStudentById(id);
        mv.addObject("headerMessage", "Редактирование студента");
        mv.addObject("student", student);
        return mv;
    }
 
    @PostMapping(value = "/editStudent")
    public String saveEditedUser(
            @RequestParam("id") Long id,
            @RequestParam("name") String name,
            @RequestParam("surname") String surname,
            @RequestParam("avatar") MultipartFile file) {
 
        try {
 
            studentService.updateStudent(name, surname, file, studentService.getStudentById(id));
 
        } catch (FileSystemException ex) {
            ex.printStackTrace();
        } catch (IOException e) {
            return "redirect:/error";
        }
 
        return "redirect:/allStudents";
    }
 
    @GetMapping(value = "/deleteStudent/{id}")
    public ModelAndView deleteUserById(@PathVariable Long id) {
        studentService.deleteStudentById(id);
        ModelAndView mv = new ModelAndView("redirect:/allStudents");
 
        return mv;
 
    }
 
}
mvc-dispatcher-servlet
Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<?xml version="1.0" encoding="UTF-8"?>
<beans
    xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans  
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  
    http://www.springframework.org/schema/context  
    http://www.springframework.org/schema/context/spring-context-3.0.xsd">
    
    <context:component-scan base-package="adil.java.schoolmaven" />
    
    <!-- Resolves Views Selected For Rendering by @Controllers to *.jsp Resources in the /WEB-INF/ Folder -->
    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/views/" />
        <property name="suffix" value=".jsp" />
    </bean>
</beans>
0
IT_Exp
Эксперт
34794 / 4073 / 2104
Регистрация: 17.06.2006
Сообщений: 32,602
Блог
07.06.2019, 06:25
Ответы с готовыми решениями:

Как сделать правильную авторизацию
Как сделать правильную авторизацию, я не очень понимаю как все должно работать. Я сделал сайт, использовал play фреймворк. Как правильно...

Как правильно сделать авторизацию на сессиях для одновременного залогинивания?
Не смог придумать, долее удобочитаемого заголовка. Смысл такой: Делаю авторизацию на сессиях Все по хрестоматийным примерам ...

Помогите сделать авторизацию правильно
Доборого времени суток.Захотелось зделать стандартную вещь,чтобы пользователь введя логинчик и парольчик(которые хранятся в бедешечке)...

2
 Аватар для reisal78
944 / 687 / 230
Регистрация: 28.04.2013
Сообщений: 1,925
07.06.2019, 07:25
Fallen1999, Погуглите тему spring security
0
1 / 1 / 0
Регистрация: 09.01.2019
Сообщений: 76
07.06.2019, 12:23  [ТС]
admin.jsp
Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ page language="java" session="true" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
 
 
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Secure page</title>    
    </head>
    <body>
        <h1>Title : ${title}</h1>
        <h1>Message : ${message}</h1>
        
        <!-- displaying the logged in user details. -->
        <c:if test="${pageContext.request.userPrincipal.name != null}">         
           <span>Welcome: ${pageContext.request.userPrincipal.name}</span> | <span><a id="logout" href="${pageContext.servletContext.contextPath}/logout">Logout</a></span>
        </c:if>
    </body>
</html>
login.jsp
Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
 
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Custom login</title>
        <style type="text/css">
            .error {
                color: #ff0000;
                font-weight: bold;
            }           
            .msg {
                color: #008000;
                font-weight: bold;
            }
        </style>
    </head>
    <body>
        <h1 id="banner">Custom login form</h1>
        
        <!-- invalid credentials error msg -->
        <c:if test="${not empty error}">
            <div class="error">${error}</div>
        </c:if>
        
        <!-- logged out msg -->
        <c:if test="${not empty msg}">
            <div class="msg">${msg}</div>
        </c:if>
        
        <!-- custom login form -->
        <form name="loginform" action="<c:url value='/login'/>" method="POST">
            <table>
                <tr>
                    <td>Логин:</td>        <!-- Enter username -->
                    <td><input type='text' name='username' value=''></td>
                </tr>
                <tr>
                    <td>Пароль:</td>          <!-- Enter password -->
                    <td><input type='password' name='password' /></td>
                </tr>
                <tr>
                    <td colspan="2">&nbsp;</td>
                </tr>
                <tr>
                    <td colspan='2'><input name="submit" type="submit" value="Submit" /></td>
                </tr>
            </table>
        </form>
    </body>
</html>
Добавлено через 29 минут
Как можно эту конфигурацию из туториала переделать под свой проект?

Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package adil.java.schoolmaven.config;
 
@Configuration
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
 
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter
{
   
 
    private final MyBasicAuthenticationEntryPoint customBasicAuthenticationEntryPoint;
 
    @Autowired
    public SecurityConfig(MyBasicAuthenticationEntryPoint customBasicAuthenticationEntryPoint)
    {
        
        this.customBasicAuthenticationEntryPoint = customBasicAuthenticationEntryPoint;
}
@Override
    public void configure(AuthenticationManagerBuilder auth)
    {
        auth.authenticationProvider(getDaoAuthenticationProvider());
    }
 
  
 
    /* BCrypt strength should 12 or more*/
    @Bean
    public PasswordEncoder getBCryptPasswordEncoder()
    {
        return new BCryptPasswordEncoder(12);
    }
 
    @Override
    protected void configure(HttpSecurity http) throws Exception
    {
            http.authorizeRequests()
                    .antMatchers("/anonymous*").anonymous()
                    .antMatchers("/register").permitAll()
                    .antMatchers("/users/**").hasAuthority(AuthorityConstants.ADMIN)
                    .antMatchers("/admin**").hasAuthority(AuthorityConstants.ADMIN)
                    .antMatchers("/profile/**").hasAuthority(AuthorityConstants.USER)
                    .antMatchers("/api/**").hasAnyAuthority(AuthorityConstants.API_USER,AuthorityConstants.ADMIN)
                    .antMatchers("/dba/**").hasAuthority(AuthorityConstants.DBA)
                    .anyRequest().authenticated()
            .and()
                    .httpBasic()
            .and()
                    .exceptionHandling()
                    .authenticationEntryPoint(customBasicAuthenticationEntryPoint)
            .and()
                    .formLogin()
                        .loginPage("/login")
                        .loginProcessingUrl("/login")
                    .successHandler(new CustomAuthenticationSuccessHandler(sessionHistoryRepository))
                    .failureHandler(new CustomAuthenticationFailureHandler(failedLoginRepository))
                        .permitAll()
                    .and()
                    .logout()
                        .deleteCookies("X-Auth-Token")
                        .clearAuthentication(true)
                        .invalidateHttpSession(true)
                        .logoutSuccessHandler(new CustomLogoutSuccessHandler())
                        .permitAll()
             .and()
                    .exceptionHandling()
                    .accessDeniedHandler(new CustomAccessDeniedHandler(unauthorizedRequestRepository))
            .and()
                    .rememberMe().rememberMeServices(springSessionRememberMeServices());
 
        // Uses CorsConfigurationSource bean defined below
        http.cors();
 
        http.sessionManagement()
                        //.invalidSessionUrl("/login.html")
                        //.invalidSessionStrategy((request, response) -> request.logout())
                        .sessionFixation().migrateSession()
                        .maximumSessions(1)
                        .maxSessionsPreventsLogin(false)
                        .sessionRegistry(sessionRegistry());
 
        http.csrf()
            .disable();
        http.authorizeRequests()
            .antMatchers("/").permitAll()
                .and()
            .authorizeRequests().antMatchers("/console/**","/h2-console/**").permitAll();
        http.headers()
             .frameOptions().disable();
 
    }
 
    @Bean
    public SpringSessionRememberMeServices springSessionRememberMeServices()
    {
        SpringSessionRememberMeServices rememberMeServices = new SpringSessionRememberMeServices();
        rememberMeServices.setRememberMeParameterName("remember-me");
        rememberMeServices.setValiditySeconds(ApplicationConstants.REMEMBERMETIMEOUT);
        return rememberMeServices;
    }
 
    //Cors filter to accept incoming requests
   @Bean
    CorsConfigurationSource corsConfigurationSource()
    {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.applyPermitDefaultValues();
        configuration.setAllowedMethods(Collections.singletonList("*"));
        configuration.setAllowCredentials(true);
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }
 
 
    @Override
    public void configure(WebSecurity web) throws Exception
    {
        web
            .ignoring()
            .antMatchers("/resources/**", "/static/**", "/css/**", "/js/**", "/images/**","/h2-console/**","/console/**");
    }
 
 
    @Bean("authenticationManager")
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception
    {
        return super.authenticationManagerBean();
    }
 
    @Bean
    public SessionRegistry sessionRegistry()
    {
        return new SessionRegistryImpl();
    }
 
}
0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
BasicMan
Эксперт
29316 / 5623 / 2384
Регистрация: 17.02.2009
Сообщений: 30,364
Блог
07.06.2019, 12:23
Помогаю со студенческими работами здесь

Как правильно реализовать авторизацию
У меня на сайте есть что-то подобное авторизации. С определенной страницы, введя логин и пароль, должна открыватся страница с информацией....

Как правильно реализовать авторизацию пользователя?
Решил попробовать написать свою CMS просто так. Не понимаю как авторизировать пользователя. Подскажите.

Как правильно организовать авторизацию к MS SQL
День добрый. Прошу помочь советом /ссылкой /статьей / примером. Вопрос заключается в след. Необходимо написать приложение...

Как правильно создать авторизацию по email или телефону?
есть авторизация по емейлу хочу переделать по емейлу или номеру телефона $result = $mysqli-&gt;query(&quot;SELECT * FROM `users`...

Как правильно реализовать авторизацию пользователя WIF и MVC
Не давно начал исследованные по поводу WIF (Windows Identity Foundation). Вроде технология заманчивая. Но из-за трудности понимания того,...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
3
Ответ Создать тему
Новые блоги и статьи
Реалии
Hrethgir 01.03.2026
Нет, я не закончил до сих пор симулятор. Эта задача сложнее. Не получилось уйти в плавсостав, но оно и к лучшему, возможно. Точнее получалось - но сварщиком в палубную команду, а это значит, в моём. . .
Ритм жизни
kumehtar 27.02.2026
Иногда приходится жить в ритме, где дел становится всё больше, а вовлечения в происходящее — всё меньше. Плотный график не даёт вниманию закрепиться ни на одном событии. Утро начинается с быстрых,. . .
SDL3 для Web (WebAssembly): Сборка SDL3, Box2D, FreeType и SDL3_ttf из исходников с помощью CMake и Emscripten
8Observer8 27.02.2026
Недавно вышла версия 3. 4. 2 библиотеки SDL3. На странице официальной релиза доступны исходники, готовые DLL (для x86, x64, arm64), а также библиотеки для разработки под Android, MinGW и Visual Studio. . . .
SDL3 для Web (WebAssembly): Реализация движения на Box2D v3 - трение и коллизии с повёрнутыми стенами
8Observer8 20.02.2026
Содержание блога Box2D позволяет легко создать главного героя, который не проходит сквозь стены и перемещается с заданным трением о препятствия, которые можно располагать под углом, как верхнее. . .
Конвертировать закладки radiotray-ng в m3u-плейлист
damix 19.02.2026
Это можно сделать скриптом для PowerShell. Использование . \СonvertRadiotrayToM3U. ps1 <path_to_bookmarks. json> Рядом с файлом bookmarks. json появится файл bookmarks. m3u с результатом. # Check if. . .
Семь CDC на одном интерфейсе: 5 U[S]ARTов, 1 CAN и 1 SSI
Eddy_Em 18.02.2026
Постепенно допиливаю свою "многоинтерфейсную плату". Выглядит вот так: https:/ / www. cyberforum. ru/ blog_attachment. php?attachmentid=11617&stc=1&d=1771445347 Основана на STM32F303RBT6. На борту пять. . .
Камера Toupcam IUA500KMA
Eddy_Em 12.02.2026
Т. к. у всяких "хикроботов" слишком уж мелкий пиксель, для подсмотра в ESPriF они вообще плохо годятся: уже 14 величину можно рассмотреть еле-еле лишь на экспозициях под 3 секунды (а то и больше),. . .
И ясному Солнцу
zbw 12.02.2026
И ясному Солнцу, и светлой Луне. В мире покоя нет и люди не могут жить в тишине. А жить им немного лет.
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru