Всем добрый вечер. Пытаюсь разобраться с rest авторизацией используя Spring Security.
Итак:
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();
}
}
Если пользователь не залогинился, вызывается:
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();
}
}
Если залогинился, но не соответствует роль, то:
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, показывает
1.
{"error":"Unauthorized!"}
- все как положено.
Теперь самое интересное. Для логина я использую метод контроллера:
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){
}
......
Модель запроса:
1.
2.
3.
LoginRequest {
private LoginUserInfo loginUserInfo;
...
где:
1.
2.
3.
4.
5.
LoginUserInfo {
private Long id;
private String login;
private String password;
private UserType userType;
Я не могу понять, что должно находиться в методе login, чтобы все это связать с spring security?
Правильно ли я понимаю, что в login нужно сделать что-то типа:
1.
MyUser myUser = userService.findByLoginAndPassword(loginRequest.getLoginUserInfo().getLogin(), loginRequest.getLoginUserInfo().getPassword());
и далее положить этот myUser в SecurityContextHolder?
Помогите разобраться. Спасибо!