Я реализую безопасность Spring с загрузкой Spring и Oauth2 с загрузкой Spring версии 1.5.12.RELEASE
При получении этой ошибки будет пытаться получить токен доступа
Hibernate: select user0_.id as id1_1_, user0_.email as email2_1_, user0_.mobilenumber as mobilenu3_1_, user0_.password as password4_1_, user0_.role_id as role_id6_1_, user0_.username as username5_1_ from user user0_ where user0_.username=?
2018-04-25 10: 17: 39.707 INFO 16592 --- [nio-8080-exec-1]
o.s.s.o.provider.endpoint.TokenEndpoint: Ошибка обработки:
InternalAuthenticationServiceException, null
org.springframework.security.authentication.InternalAuthenticationServiceException
в
org.springframework.security.authentication.dao.DaoAuthenticationProvider.retrieveUser (DaoAuthenticationProvider.java:126)
в
org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider.authenticate (AbstractUserDetailsAuthenticationProvider.java:144)
в
org.springframework.security.authentication.ProviderManager.authenticate (ProviderManager.java:174)
в
org.springframework.security.oauth2.provider.password.ResourceOwnerPasswordTokenGranter.getOAuth2Authentication (ResourceOwnerPasswordTokenGranter.java:71)
в
org.springframework.security.oauth2.provider.token.AbstractTokenGranter.getAccessToken (AbstractTokenGranter.java:70)
в
org.springframework.security.oauth2.provider.token.AbstractTokenGranter.grant (AbstractTokenGranter.java:65)
в
org.apache.catalina.valves.ErrorReportValve.invoke (ErrorReportValve.java:81)
в
org.apache.catalina.core.StandardEngineValve.invoke (StandardEngineValve.java:87)
в
org.apache.catalina.connector.CoyoteAdapter.service (CoyoteAdapter.java:342)
в
org.apache.coyote.http11.Http11Processor.service (Http11Processor.java:803)
в
org.apache.coyote.AbstractProcessorLight.process (AbstractProcessorLight.java:66)
в
org.apache.coyote.AbstractProtocol $ ConnectionHandler.process (AbstractProtocol.java:790)
в
org.apache.tomcat.util.net.NioEndpoint $ SocketProcessor.doRun (NioEndpoint.java:1459)
в
org.apache.tomcat.util.net.SocketProcessorBase.run (SocketProcessorBase.java:49)
в
java.util.concurrent.ThreadPoolExecutor.runWorker (ThreadPoolExecutor.java:1149)
в
java.util.concurrent.ThreadPoolExecutor $ Worker.run (ThreadPoolExecutor.java:624)
в
org.apache.tomcat.util.threads.TaskThread $ WrappingRunnable.run (TaskThread.java:61)
at java.lang.Thread.run (Thread.java:748) Причина:
java.lang.NullPointerException в
com.vp.learning.SpringSecurityDemo.model.CustomUserDetails. (CustomUserDetails.java:21)
в
com.vp.learning.SpringSecurityDemo.SpringSecurityDemoApplication.lambda $ 0 (SpringSecurityDemoApplication.java:42)
в
org.springframework.security.authentication.dao.DaoAuthenticationProvider.retrieveUser (DaoAuthenticationProvider.java:114)
... еще 107
Мои классы выглядят так
AuthorizationServerConfig
@ конфигурации
@EnableAuthorizationServer
открытый класс AuthorizationServerConfig расширяет AuthorizationServerConfigurerAdapter {
@Autowired
AuthenticationManager authenticationManager;
@Autowired
public PasswordEncoder passwordEncoder;
@Override
public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
// TODO Auto-generated method stub
security.checkTokenAccess("isAuthenticated()");
}
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
// TODO Auto-generated method stub
clients.inMemory().withClient("my-client-id")
.authorizedGrantTypes("client-credentials","password")
.authorities("ROLE_CLIENT","ROLE_TRUSTED_CLIENT")
.scopes("read","write","trust")
.resourceIds("oauth2-resource")
.accessTokenValiditySeconds(500)
.secret("secret");
}
@Bean
public WebResponseExceptionTranslator loggingExceptionTranslator() {
return new DefaultWebResponseExceptionTranslator() {
@Override
public ResponseEntity<OAuth2Exception> translate(Exception e) throws Exception {
// This is the line that prints the stack trace to the log. You can customise this to format the trace etc if you like
e.printStackTrace();
// Carry on handling the exception
ResponseEntity<OAuth2Exception> responseEntity = super.translate(e);
HttpHeaders headers = new HttpHeaders();
headers.setAll(responseEntity.getHeaders().toSingleValueMap());
OAuth2Exception excBody = responseEntity.getBody();
return new ResponseEntity<>(excBody, headers, responseEntity.getStatusCode());
}
};
}
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.authenticationManager(authenticationManager) .exceptionTranslator(loggingExceptionTranslator());
}
}
ResourceServerConfig
@Configuration
@ EnableResourceServer
открытый класс ResourceServerConfig расширяет ResourceServerConfigurerAdapter {
@Override
public void configure(HttpSecurity http) throws Exception {
// TODO Auto-generated method stub
http.headers().frameOptions().disable().and()
.authorizeRequests()
.antMatchers("/","/h2_console","/register","/login").permitAll()
.antMatchers("/secure/**").authenticated();
}
}
SpringSecurityDemoApplication.java
@SpringBootApplication
открытый класс SpringSecurityDemoApplication {
@Autowired
private PasswordEncoder passwordEncoder;
public static void main(String[] args) {
SpringApplication.run(SpringSecurityDemoApplication.class, args);
}
@Autowired
public void authenticationManager(AuthenticationManagerBuilder builder, UserRepository repository, UserService service) throws Exception {
//Setup a default user if db is empty
if (repository.count()==0)
service.save(new User("user", "user", new Role("USER")));
User u =repository.findByUsername("user");
System.out.println(u);
builder.userDetailsService(userDetailsService(repository)).passwordEncoder(passwordEncoder);
}
/**
* We return an istance of our CustomUserDetails.
* @param repository
* @return
*/
private UserDetailsService userDetailsService(final UserRepository repository) {
return username -> new CustomUserDetails(repository.findByUsername(username));
}
}
CustomUserDetails
public class CustomUserDetails implements UserDetails {
/**
*
*/
private String username;
private String password;
private Collection<? extends GrantedAuthority> authorities;
public CustomUserDetails(User byUsername) {
this.username = byUsername.getUsername();
this.password =byUsername.getPassword();
this.authorities = translate(byUsername.getRole());
}
private Collection<? extends GrantedAuthority> translate(Role roles) {
List<GrantedAuthority> authorities = new ArrayList<>();
authorities.add(new SimpleGrantedAuthority("ROLE_"+roles.getName()));
return authorities;
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
// TODO Auto-generated method stub
return authorities;
}
@Override
public String getPassword() {
// TODO Auto-generated method stub
return password;
}
@Override
public String getUsername() {
// TODO Auto-generated method stub
return username;
}
@Override
public boolean isAccountNonExpired() {
// TODO Auto-generated method stub
return true;
}
@Override
public boolean isAccountNonLocked() {
// TODO Auto-generated method stub
return true;
}
@Override
public boolean isCredentialsNonExpired() {
// TODO Auto-generated method stub
return true;
}
@Override
public boolean isEnabled() {
// TODO Auto-generated method stub
return true;
}
}
Определены и другие классы
Вот как я бью по остальному API
введите описание изображения здесь