首页 > 解决方案 > 获取错误将使用 Spring Security 访问 oauth 令牌,并使用 oauth2 进行 Spring Boot

问题描述

我正在使用 Spring Boot 实现 Spring 安全性,并使用 Spring Boot Release 1.5.12.RELEASE 实现 Oauth2

收到此错误将尝试获取访问令牌

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] ossoprovider.endpoint.TokenEndpoint:处理错误:InternalAuthenticationServiceException,空 org.springframework.security.authentication.InternalAuthenticationServiceException 在 org.springframework。 security.authentication.dao.DaoAuthenticationProvider.retrieveUser(DaoAuthenticationProvider.java:126) at org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider.authenticate(AbstractUserDetailsAuthenticationProvider.java:144) at 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。在 org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342) 在 org.apache.catalina.invoke(StandardEngineValve.java:87) 在 org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87) 调用(ErrorReportValve.java:81) .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 的 org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1459)。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) 原因:com.vp 的 java.lang.NullPointerException .learning.SpringSecurityDemo.model.CustomUserDetails.(CustomUserDetails.java:21) at com.vp.learning.SpringSecurityDemo.SpringSecurityDemoApplication.lambda$0(SpringSecurityDemoApplication.java:42) at org.springframework.security.authentication.dao.DaoAuthenticationProvider.retrieveUser (DaoAuthenticationProvider.java:114) ... 107 更多java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run( TaskThread.java:61) 在 java.lang.Thread.run(Thread.java:748) 引起:com.vp.learning.SpringSecurityDemo.model.CustomUserDetails.(CustomUserDetails.java:21) 的 java.lang.NullPointerException com.vp.learning.SpringSecurityDemo.SpringSecurityDemoApplication.lambda$0(SpringSecurityDemoApplication.java:42) at org.springframework.security.authentication.dao.DaoAuthenticationProvider.retrieveUser(DaoAuthenticationProvider.java:114) ... 107 更多java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run( TaskThread.java:61) 在 java.lang.Thread.run(Thread.java:748) 引起:com.vp.learning.SpringSecurityDemo.model.CustomUserDetails.(CustomUserDetails.java:21) 的 java.lang.NullPointerException com.vp.learning.SpringSecurityDemo.SpringSecurityDemoApplication.lambda$0(SpringSecurityDemoApplication.java:42) at org.springframework.security.authentication.dao.DaoAuthenticationProvider.retrieveUser(DaoAuthenticationProvider.java:114) ... 107 更多run(ThreadPoolExecutor.java:624) at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) at java.lang.Thread.run(Thread.java:748) 原因:java .lang.NullPointerException at com.vp.learning.SpringSecurityDemo.model.CustomUserDetails.(CustomUserDetails.java:21) at com.vp.learning.SpringSecurityDemo.SpringSecurityDemoApplication.lambda$0(SpringSecurityDemoApplication.java:42) at org.springframework.security .authentication.dao.DaoAuthenticationProvider.retrieveUser(DaoAuthenticationProvider.java:114) ... 107 更多run(ThreadPoolExecutor.java:624) at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) at java.lang.Thread.run(Thread.java:748) 原因:java .lang.NullPointerException at com.vp.learning.SpringSecurityDemo.model.CustomUserDetails.(CustomUserDetails.java:21) at com.vp.learning.SpringSecurityDemo.SpringSecurityDemoApplication.lambda$0(SpringSecurityDemoApplication.java:42) at org.springframework.security .authentication.dao.DaoAuthenticationProvider.retrieveUser(DaoAuthenticationProvider.java:114) ... 107 更多java:21) at com.vp.learning.SpringSecurityDemo.SpringSecurityDemoApplication.lambda$0(SpringSecurityDemoApplication.java:42) at org.springframework.security.authentication.dao.DaoAuthenticationProvider.retrieveUser(DaoAuthenticationProvider.java:114) ... 107 更多java:21) at com.vp.learning.SpringSecurityDemo.SpringSecurityDemoApplication.lambda$0(SpringSecurityDemoApplication.java:42) at org.springframework.security.authentication.dao.DaoAuthenticationProvider.retrieveUser(DaoAuthenticationProvider.java:114) ... 107 更多

我的课程看起来像这样 AuthorizationServerConfig

@Configuration @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());

}

}

资源服务器配置

@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));
}

}

自定义用户详细信息

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 的方式

在此处输入图像描述

标签: javaspring-bootspring-securityoauth-2.0

解决方案


推荐阅读