如何在控制器方法中使用Principal
对象作为参数,而不是使用SecurityContextHolder.getContext().getAuthentication().getPrincipal()
我使用spring 4,spring mvc
我的休息控制器
@RestController
@Api(value = "Dictionary Resource")
@RequestMapping("/test")
public class TestControllerImpl {
@RequestMapping(value = "test", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.ALL_VALUE)
public TestDTO test(Principal principal) {
System.out.println("principal = "+principal.getName()); // this is null pointner exception, principal is null, but i want this use
Principal principal1 = (Principal)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
System.out.println("principal1() = "+principal1.getName()); // this work fine
}
}
我有类HandlerInterceptor如下:
@Component
public class MyHandlerInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
MyAuthentication auth= MyAuthentication.builder().login("admin").build();
SecurityContextHolder.getContext().setAuthentication(auth);
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
}
}
使用Principal
的身份验证类@Data
@Builder
public class MyAuthentication implements Authentication{
private String login;
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
List<GrantedAuthority> authorities = new ArrayList<>(1);
authorities.add(new SimpleGrantedAuthority("ROLE_USER"));
return authorities;
}
@Override
public Object getCredentials() {
return null;
}
@Override
public Object getDetails() {
return null;
}
@Override
public Object getPrincipal() {
return (Principal)() -> login;
}
@Override
public boolean isAuthenticated() {
return true;
}
@Override
public void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException {
}
@Override
public String getName() {
return login;
}
public static Principal getCurrentPrincipal(){
return (Principal) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
}
}