powered by simpleCommunicator - 2.0.61     © 2026 Programmizd 02
Целевая тема:
Создать новую тему:
Автор:
Закрыть
Цитировать
Форумы / Java [игнор отключен] [закрыт для гостей] / Spring security - rest авторизация
1 сообщений из 1, страница 1 из 1
Spring security - rest авторизация
    #39169789
JulT
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Всем добрый вечер. Пытаюсь разобраться с rest авторизацией используя Spring Security.
Итак:
Код: 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.
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true) 
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    @Qualifier("userDetailsService")
    private UserDetailsService userDetailsService;

    @Autowired
    private RestAuthenticationEntryPoint authenticationEntryPoint;
    @Autowired
    private RestAuthenticationSuccessHandler restAuthenticationSuccessHandler;
    @Autowired
    private RestAuthenticationAccessDeniedHandler restAuthenticationAccessDeniedHandler;


    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService); 
    }

    
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .csrf().disable()
                .exceptionHandling()
                .authenticationEntryPoint(authenticationEntryPoint)
                .and()
                .authorizeRequests()
                .antMatchers("/admin/**").authenticated()
                .and()
                .formLogin()
                .successHandler(restAuthenticationSuccessHandler)
                .failureHandler(restAuthenticationAccessDeniedHandler)
                .and()
                .logout();
    } 
}




Если пользователь не залогинился, вызывается:

Код: java
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
@Component
public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws 

IOException {

        response.getWriter().print("{\"error\":\"Unauthorized!\"}");
        response.getWriter().flush();
    }
}


Если залогинился, но не соответствует роль, то:
Код: java
1.
2.
3.
4.
5.
6.
7.
8.
@Component
public class RestAuthenticationAccessDeniedHandler extends SimpleUrlAuthenticationFailureHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException e) throws IOException, 

ServletException {
        response.getWriter().print("{\"error\":\"Access denied!\"}");
    }



Запускаю, пробую зайти на admin/test, показывает
Код: java
1.
{"error":"Unauthorized!"} 

- все как положено.
Теперь самое интересное. Для логина я использую метод контроллера:
Код: java
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
@Controller
@RequestMapping("/auth")
public class AuthController {

@Autowired
private UserService userService;

@RequestMapping(value = "/login", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public LoginResponse login(@RequestBody LoginRequest loginRequest, HttpServletRequest request){
     
}
......



Модель запроса:
Код: java
1.
2.
3.
LoginRequest {
    private LoginUserInfo loginUserInfo;
...


где:
Код: java
1.
2.
3.
4.
5.
LoginUserInfo {
    private Long id;
    private String login;
    private String password;
    private UserType userType;


Я не могу понять, что должно находиться в методе login, чтобы все это связать с spring security?
Правильно ли я понимаю, что в login нужно сделать что-то типа:
Код: java
1.
MyUser myUser = userService.findByLoginAndPassword(loginRequest.getLoginUserInfo().getLogin(), loginRequest.getLoginUserInfo().getPassword());    


и далее положить этот myUser в SecurityContextHolder?
Помогите разобраться. Спасибо!
...
Рейтинг: 0 / 0
1 сообщений из 1, страница 1 из 1
Форумы / Java [игнор отключен] [закрыт для гостей] / Spring security - rest авторизация
Найденые пользователи ...
Разблокировать пользователей ...
Читали форум (0):
Пользователи онлайн (0):
x
x
Закрыть


Просмотр
0 / 0
Close
Debug Console [Select Text]