Я использую пользовательский AuthenticationProvider
и возвращаю пользовательский AuthenticationToken
.
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
String username = authentication.getName();
String password = authentication.getCredentials().toString();
DBUser dbUser = userDao.getUserLDAP(username);
//check password
return new CustomAuthenticationToken(dbUser, password, grantedAuthorities);
}
CustomAuthenticationToken:
public class CustomAuthenticationToken extends AbstractAuthenticationToken {
private DBUser principal;
private String credential;
public CustomAuthenticationToken(DBUser dbUser, String password, Collection<? extends GrantedAuthority> authorities) {
super(authorities);
this.setDetails(dbUser);
this.principal = dbUser;
this.credential = password;
this.setAuthenticated(true);
}
//getters, setters
}
Но пока я пытаюсь сделать в контроллере:
@GetMapping("/user/current")
public ResponseEntity<Object> currentUser(@AuthenticationPrincipal DBUser dbUser){
return ResponseEntity.ok(dbUser);
}
dbUser
равно нулю, так как AuthenticationPrincipalArgumentResolver
в методе resolveArguments
public Object resolveArgument(MethodParameter parameter,
ModelAndViewContainer mavContainer, NativeWebRequest
webRequest, WebDataBinderFactory binderFactory) throws
Exception {
Authentication authentication =
SecurityContextHolder.getContext().getAuthentication();
if (authentication == null) {
return null;
} else {
Object principal = authentication.getPrincipal();
authentication.userAuthentication
является экземпляром UsernamePasswordAuthenticationToken
(не мой возвращенный обычай).
Как я могу поставить токены на детали, а затем получить их в контексте безопасности?
Я использую Spring Security oauth2 + JWT.
Конфигурация безопасности:
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private CustomAuthenticationProvider authenticationProvider;
@Override
protected void configure(AuthenticationManagerBuilder auth) {
auth.authenticationProvider(authenticationProvider);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.anyRequest()
.authenticated()
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.NEVER);
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/v2/api-docs",
"/configuration/ui",
"/swagger-resources",
"/configuration/security",
"/swagger-ui.html",
"/webjars/**");
}
@Override
@Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
}
OAuth config:
@Configuration
@EnableAuthorizationServer
public class OAuthConfig extends AuthorizationServerConfigurerAdapter {
private static final String CLIENT_ID = "client";
private static final String CLIENT_SECRET = "pwd";
@Autowired
@Qualifier("authenticationManagerBean")
private AuthenticationManager authenticationManager;
@Bean
public JwtAccessTokenConverter tokenEnhancer() {
JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
converter.setSigningKey(Keys.PRIVATE_KEY);
converter.setVerifierKey(Keys.PUBLIC_KEY);
return converter;
}
@Bean
public JwtTokenStore tokenStore() {
return new JwtTokenStore(tokenEnhancer());
}
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
endpoints.authenticationManager(authenticationManager)
.tokenStore(tokenStore())
.accessTokenConverter(tokenEnhancer());
}
@Override
public void configure(AuthorizationServerSecurityConfigurer security) {
security.tokenKeyAccess("permitAll()").checkTokenAccess("isAuthenticated()");
}
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory()
.withClient(CLIENT_ID)
.secret(new BCryptPasswordEncoder().encode(CLIENT_SECRET))
.scopes("read", "write")
.authorizedGrantTypes("authorization_code", "refresh_token", "password")
.scopes("openid")
.autoApprove(true)
.accessTokenValiditySeconds(20000)
.refreshTokenValiditySeconds(20000);
}
}
Thx.