【发布时间】:2025-11-22 13:00:02
【问题描述】:
我实现自定义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);
}
自定义身份验证令牌:
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 配置:
@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);
}
}
谢谢。
【问题讨论】:
-
您的 DBUser 是否实现了 Oauth2?类 DBUser 实现 OAuth2User,UserDetails {...}
-
否,但我尝试实施 UserDetails 并没有任何结果
-
您的问题只是您的自定义身份验证提供程序和您的自定义身份验证令牌。还显示您的自定义过滤器。还显示您的身份验证提供商的
supports方法。 -
我还没有附加过滤器,因为 jwt 令牌没有详细信息文件。 “支持”是什么意思?
-
你能添加你的 spring 安全配置类吗?
标签: java spring spring-security