【发布时间】:2016-08-31 23:50:52
【问题描述】:
我对 Spring 还是很陌生,尤其是 Spring Security。本应用为 Restful 应用。
下面是来自@RestController的sn-p:
@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的sn-p:
@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 在控制器之外(我猜)。
【问题讨论】:
标签: spring spring-mvc authentication spring-security