我对 Spring 尤其是 Spring Security 还很陌生。此应用程序是 Restful 应用程序。
以下是来自 @RestController
的片段:
@RequestMapping(value = "/new", method = RequestMethod.POST)
@PreRegistration("new")
@ResponseBody
public ResponseEntity<Void> newUser(@RequestBody @Valid TempUser user, UriComponentsBuilder ucBuilder) {
registerService.addUser(user);
HttpHeaders headers = new HttpHeaders();
headers.setLocation(ucBuilder.path("/register/{userName}").buildAndExpand(user.getUserName()).toUri());
return new ResponseEntity<Void>(headers, HttpStatus.CREATED);
}
以下是来自 CustomAuthenticationProvider
的片段:
@Override
public Authentication authenticate(final Authentication authentication) throws AuthenticationException {
final String name = authentication.getName();
final String password = authentication.getCredentials().toString();
if (name.equals("admin") && password.equals("system")) {
final List<GrantedAuthority> grantedAuths = new ArrayList<>();
grantedAuths.add(new SimpleGrantedAuthority("ROLE_USER"));
final UserDetails principal = new User(name, password, grantedAuths);
final Authentication auth = new UsernamePasswordAuthenticationToken(principal, password, grantedAuths);
return auth;
}
else {
throw new BadCredentialsException("NOT_AUTHORIZED");
}
}
安全配置:
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.anyRequest().authenticated()
.and()
.requestCache()
.requestCache(new NullRequestCache())
.and()
.httpBasic()
.and()
.csrf().disable();
}
我试图实现的是,当 CustomAuthenticationProvider
抛出异常时(例如“错误凭证”或“需要完全身份验证...”,我想自定义响应并返回到响应正文JSON 格式。
我所做的是创建一个新的异常并使用 AOP 调用它。但似乎不起作用。我还尝试使用 @ControllerAdvice,但它似乎不起作用,因为 CustomAuthenticationProvider
位于 Controller 之外(我猜)。
最佳答案
对此有更好的方法。您应该在 spring security 配置和类中添加 authenticationEntryPoint
,它实现 AuthenticationEntryPoint
接口(interface)。像这样的事情:
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/login").permitAll()
.anyRequest().authenticated()
.and()
.requestCache()
.requestCache(new NullRequestCache())
.and()
.httpBasic()
// --> begin change: new lines added
.and()
.exceptionHandling().authenticationEntryPoint(new AuthExceptionEntryPoint())
// <-- end change
.and()
.csrf().disable();
}
AuthExceptionEntryPoint 类,用于生成 JSON Jackson使用的ObjectMapper
:
public class AuthExceptionEntryPoint implements AuthenticationEntryPoint {
@Override
public void commence(HttpServletRequest request, HttpServletResponse response,
AuthenticationException authException)
throws IOException, ServletException {
List<String> errors = new ArrayList<>();
errors.add("Unauthorized");
response.setContentType("application/json");
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
try {
ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(response.getOutputStream(), errors);
} catch (Exception e) {
throw new ServletException();
}
}
}
有关 Spring Security 配置的更多信息,您可以阅读 Spring docs
关于Spring security with @RestController - JSONish CustomAuthenticationProvider 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37063342/