springboot oauth如何验证access_token

时间:2019-01-08 09:04:26

标签: spring-boot oauth

大家好,希望您一切顺利,

我在春季引导中使用开放式身份验证时遇到问题,当使用邮递员访问页面休息甚至不使用param访问令牌时,它仍然显示结果,这对我的代码有帮助吗?

授权服务器配置类:

@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends 
AuthorizationServerConfigurerAdapter{
@Autowired
private AuthenticationManager authenticationManager;

@Autowired
private TokenStore tokenStore;
@Autowired
private UserApprovalHandler userApprovalHandler;

@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) 
throws Exception {

  endpoints.tokenStore(tokenStore).userApprovalHandler(userApprovalHandler);
    endpoints.authenticationManager(authenticationManager);
}
@Override
public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
    security
            .tokenKeyAccess("permitAll()")
            .checkTokenAccess("isAuthenticated()")
            .allowFormAuthenticationForClients();
}

@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
    // TODO Auto-generated method stub
    clients.inMemory()
    .withClient("admin").secret("123")
    .scopes("read","write")
    .authorizedGrantTypes("password","refresh_token")
    .accessTokenValiditySeconds(5*60)
    .refreshTokenValiditySeconds(10*60);
}

}

资源服务器配置

@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter{
    @Override
    public void configure(HttpSecurity http)throws Exception{
        http
            .anonymous().disable()
            .authorizeRequests().antMatchers("/api/**") /** this
            .authenticated()
            .and()
            .exceptionHandling().accessDeniedHandler(new OAuth2AccessDeniedHandler());
    }
}

安全配置

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private DataSource dataSource;
    @Autowired
    private SecurityUtility hash;
    @Autowired
    private ClientDetailsService clientDetailsService;

    private static final String[] PUBLIC_MATCHERS = { "/", "/css/**", "/image/**", "/js/**", "/newUser",
            "/forgetPassword", "/login", "/logout", "/fonts/**", "/signUp", "/register", "/sendEmail", "/logout", "/tes","/oauth2/**","/api/**",
            "/admin/tes","/SpringSecurityOAuth2Example/**",
            "/admin/tes2" };
    private static final String[] ADMIN_MATCHERS = { "/admin", "/admin/**" };
    private static final String[] OAUTH2_PAGE = { "/oauth/**", "/api/**" };

    private final String USERS_QUERY = "select username, password, is_enabled from user where username=?";
    private final String ROLES_QUERY = "select u.username, u.is_enabled, r.name as authority from user u "
            + "inner join user_role ur on (u.id = ur.user_id) " + "inner join role r on (ur.role_id = r.roleid) "
            + "where username=?";

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers(PUBLIC_MATCHERS).permitAll().anyRequest().authenticated().and().formLogin()
                .loginPage("/login").loginProcessingUrl("/app-login").usernameParameter("app_username")
                .passwordParameter("app_password").defaultSuccessUrl("/myAccount").permitAll()
                .and().logout().logoutSuccessUrl("/login")
                .permitAll();
        http.authorizeRequests().antMatchers(ADMIN_MATCHERS).hasRole("ADMIN");
//      http.csrf().disable();
        http.csrf().ignoringAntMatchers(OAUTH2_PAGE);
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        // temporary
        // auth.inMemoryAuthentication().withUser("admin").password("admin").roles("test");
        auth.jdbcAuthentication().usersByUsernameQuery(USERS_QUERY).authoritiesByUsernameQuery(ROLES_QUERY)
                .dataSource(dataSource).passwordEncoder(hash.passwordEncoder());
    }

    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }


    @Bean
    public TokenStore tokenStore() {
        return new InMemoryTokenStore();
    }

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

}

身份验证控制器

@RestController
@EnableResourceServer
public class AuthController {
    @GetMapping("/api/demo1")
    public String apiTes() {
        System.out.println("sysout mas");
        return "return result";
    }
}

postman result without params

1 个答案:

答案 0 :(得分:0)

解决了,因为我使用的是springboot 1.5.10,所以我必须添加

  

security.oauth2.resource.filter-order = 3

跳转到application.properties