我使用了jwt令牌oauth2。 我的自定义提供程序无法接收令牌。我在DB中找到了一个管理员,一切都很好,但是我没有收到任何令牌。我将/ oauth / authorize放在setAuthenticationSuccessHandler中,并在邮递员中看到: 来自setAuthenticationSuccessHandler的页面(我试图将/ oauth / authorize放在这里,但这没有帮助)
我应该纠正什么? ps。我尚未使用该电子邮件,因为它没有用。 定制提供程序类:
@Component
public class AdminProvider implements AuthenticationProvider {
@Autowired
private AdminRepository adminRepository;
@Autowired
private CheckPasswordWhenLogin checkPasswordWhenLogin;
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
DomainUsernamePasswordAuthenticationToken token = (DomainUsernamePasswordAuthenticationToken) authentication;
String userName = token.getName();
String domain = token.getDomain();
String checkPassword = token.getCredentials().toString();
String email = userName + "@" + domain;
Admin admin = adminRepository.findAdminByUsername(userName);
String password = admin.getPassword();
//here I check password with encode
if(!checkPasswordWhenLogin.checkPassword(checkPassword,password)) {
throw new BadCredentialsException("Invalid username/password");
}
Collection<? extends GrantedAuthority> authorities = translate();
return new DomainUsernamePasswordAuthenticationToken(admin, password, domain, authorities);
}
private Collection<? extends GrantedAuthority> translate() {
List<GrantedAuthority> authorities = new ArrayList<>();
authorities.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
return authorities;
}
@Override
public boolean supports(Class<?> authentication) {
return DomainUsernamePasswordAuthenticationToken.class.equals(authentication);
}
}
安全配置:
@Configuration
@EnableWebSecurity(debug = true)
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private ClientDetailsService clientDetailsService;
@Autowired
private AdminProvider adminProvider;
@Override
public void configure(final AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(adminProvider);
}
@Bean(name = "pass")
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Bean
public TokenStore tokenStore() {
return new JwtTokenStore(jwtTokenEnhancer());
}
@Bean
protected JwtAccessTokenConverter jwtTokenEnhancer() {
JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
converter.setSigningKey("Demo-Key-1");
return converter;
}
@Bean
@Autowired
public TokenStoreUserApprovalHandler userApprovalHandler(TokenStore tokenStore) {
TokenStoreUserApprovalHandler handler = new TokenStoreUserApprovalHandler();
handler.setTokenStore(tokenStore);
handler.setRequestFactory(new DefaultOAuth2RequestFactory(clientDetailsService));
handler.setClientDetailsService(clientDetailsService);
return handler;
}
@Bean
@Autowired
public ApprovalStore approvalStore(TokenStore tokenStore) throws Exception {
TokenApprovalStore store = new TokenApprovalStore();
store.setTokenStore(tokenStore);
return store;
}
@Override
protected void configure(final HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/admin/h2/**").permitAll()
.antMatchers("/").permitAll()
.antMatchers("/signup/*").permitAll()
.antMatchers("/errors/**").permitAll()
.antMatchers("/admin/*").hasRole("ADMIN")
.antMatchers("/events/").hasRole("ADMIN")
.antMatchers("/**").hasRole("USER")
.and().exceptionHandling()
.accessDeniedPage("/errors/403")
.authenticationEntryPoint(loginUrlAuthenticationEntryPoint())
.and().logout()
.logoutUrl("/logout")
.logoutSuccessUrl("/login/form?logout")
.permitAll()
.and().anonymous()
.and().csrf().disable()
// Add custom DomainUsernamePasswordAuthenticationFilter
.addFilterAt(domainUsernamePasswordAuthenticationFilter(),
UsernamePasswordAuthenticationFilter.class);
}
@Bean
public DomainUsernamePasswordAuthenticationFilter domainUsernamePasswordAuthenticationFilter()
throws Exception {
DomainUsernamePasswordAuthenticationFilter dupaf = new DomainUsernamePasswordAuthenticationFilter(
super.authenticationManagerBean());
dupaf.setFilterProcessesUrl("/oauth/token");
dupaf.setUsernameParameter("username");
dupaf.setPasswordParameter("password");
dupaf.setAuthenticationSuccessHandler(
new SavedRequestAwareAuthenticationSuccessHandler(){{
setDefaultTargetUrl("/my");
}}
);
dupaf.setAuthenticationFailureHandler(
new SimpleUrlAuthenticationFailureHandler(){{
setDefaultFailureUrl("/login/form?error");
}}
);
dupaf.afterPropertiesSet();
return dupaf;
}
@Bean
public LoginUrlAuthenticationEntryPoint loginUrlAuthenticationEntryPoint(){
return new LoginUrlAuthenticationEntryPoint("/login/form");
}
}
自定义UsernamePasswordAuthenticationFilter
public final class DomainUsernamePasswordAuthenticationFilter extends UsernamePasswordAuthenticationFilter {
@Autowired
public DomainUsernamePasswordAuthenticationFilter(AuthenticationManager authenticationManager){
super.setAuthenticationManager(authenticationManager);
}
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
throws AuthenticationException {
String username = obtainUsername(request);
String password = obtainPassword(request);
String domain = request.getParameter("domain");
DomainUsernamePasswordAuthenticationToken authRequest = new DomainUsernamePasswordAuthenticationToken(username,
password, domain);
setDetails(request, authRequest);
return this.getAuthenticationManager().authenticate(authRequest);
}
@Override
@Autowired
public void setAuthenticationManager(AuthenticationManager authenticationManager) {
super.setAuthenticationManager(authenticationManager);
}
}
自定义UsernamePasswordAuthenticationToken
public final class DomainUsernamePasswordAuthenticationToken extends UsernamePasswordAuthenticationToken {
private final String domain;
public DomainUsernamePasswordAuthenticationToken(String principal, String credentials, String domain) {
super(principal, credentials);
this.domain = domain;
}
public DomainUsernamePasswordAuthenticationToken(Admin principal, String credentials, String domain,
Collection<? extends GrantedAuthority> authorities) {
super(principal, credentials, authorities);
this.domain = domain;
}
public String getDomain() {
return domain;
}
private static final long serialVersionUID = -5138870746127783L;
}