我使用Spring引导实现Spring安全性,使用Spring引导版本1.5.12实现Oauth2.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) 在java.lang.Thread.run(Thread.java:748)引起: java.lang.NullPointerException at 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
@Configuration @EnableAuthorizationServer public class 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