简体   繁体   English

springboot oauth如何验证access_token

[英]springboot oauth how to validate access_token

Hello everyone hope you doing well, 大家好,希望您一切顺利,

i have problem using open authentication in spring boot, when accessing page rest with postman is not even using param access token it still show the result, this my code please help??? 我在春季启动中使用开放式身份验证时遇到问题,当用邮递员访问页面休息甚至不使用参数访问令牌时,它仍然显示结果,请问我的代码对我有帮助吗?

Authorization Server Config class: 授权服务器配置类:

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

}

Resource Server Config 资源服务器配置

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

Security Config 安全配置

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

}

Auth Controller 验证控制器

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

没有参数的邮递员结果

solved guys, it because i was using springboot 1.5.10 so i have to add 解决的家伙,这是因为我使用的是springboot 1.5.10,所以我必须添加

security.oauth2.resource.filter-order=3 security.oauth2.resource.filter阶= 3

to spring application.properties 产生application.properties

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM