微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Spring Boot OAuth2 身份验证与登录表单

如何解决Spring Boot OAuth2 身份验证与登录表单

我是 Spring Boot 和 OAuth2 的新手,我在 github 上找到了资源并尝试练习以了解更多架构和流程,所以我的配置如下:

OAuth2Configuration.java

@Configuration
public class OAuth2Configuration {

@Configuration
@EnableResourceServer
protected static class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {

    @Autowired
    private CustomAuthenticationEntryPoint customAuthenticationEntryPoint;

    @Autowired
    private CustomlogoutSuccessHandler customlogoutSuccessHandler;

    @Override
    public void configure(HttpSecurity http) throws Exception {

        http
                .exceptionHandling()
                .authenticationEntryPoint(customAuthenticationEntryPoint)
                .and()
                .logout()
                .logoutUrl("/oauth/logout")
                .logoutSuccessHandler(customlogoutSuccessHandler)
                .and()
                .csrf()
                .requireCsrfProtectionMatcher(new AntPathRequestMatcher("/oauth/authorize"))
                .disable()
                .headers()
                .frameOptions().disable()
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                .antMatchers("/secure/**","/person/**","/product/**").authenticated()
                .antMatchers(HttpMethod.GET,"/user/**").authenticated()
                .antMatchers(HttpMethod.PUT,"/user/**").authenticated()
                .antMatchers(HttpMethod.DELETE,"/user/**").authenticated()
                .antMatchers(HttpMethod.POST,"/user").permitAll();

    }

}

@Configuration
@EnableAuthorizationServer
protected static class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter implements EnvironmentAware {

    private static final String ENV_OAUTH = "authentication.oauth.";
    private static final String PROP_CLIENTID = "clientid";
    private static final String PROP_SECRET = "secret";
    private static final String PROP_TOKEN_VALIDITY_SECONDS = "tokenValidityInSeconds";

    private RelaxedPropertyResolver propertyResolver;

    @Autowired
    private DataSource dataSource;

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

    @Autowired
    @Qualifier("authenticationManagerBean")
    private AuthenticationManager authenticationManager;

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints)
            throws Exception {
        endpoints
                .tokenStore(tokenStore())
                .authenticationManager(authenticationManager);
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients
                .inMemory()
                .withClient(propertyResolver.getProperty(PROP_CLIENTID))
                .scopes("read","write")
                .authorities(Authorities.ROLE_ADMIN.name(),Authorities.ROLE_USER.name())
                .authorizedGrantTypes("password","refresh_token")
                .secret(propertyResolver.getProperty(PROP_SECRET))
                .redirectUris("http://localhost:8080/login")
                .accesstokenValiditySeconds(propertyResolver.getProperty(PROP_TOKEN_VALIDITY_SECONDS,Integer.class,1800));
    }

    @Override
    public void setEnvironment(Environment environment) {
        this.propertyResolver = new RelaxedPropertyResolver(environment,ENV_OAUTH);
    }

}

}

SecurityConfiguration.java

 @Configuration
 @EnableWebSecurity

public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

@Autowired
private UserDetailsService userDetailsService;

@Bean
public PasswordEncoder passwordEncoder() {
    // Define the type of encode
    return new BCryptPasswordEncoder();
}

@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {

    auth
            .userDetailsService(userDetailsService)
            .passwordEncoder(passwordEncoder());

}

@Override
public void configure(WebSecurity web) throws Exception {

    web
            .ignoring()
            //.antMatchers("/h2console/**")
            .antMatchers("/register")
            .antMatchers("/activate")
            .antMatchers("/lostpassword")
            .antMatchers("/resetpassword")
            //.antMatchers("/hello")
            .antMatchers("/person")
            .antMatchers("/product");

}


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

@EnableGlobalMethodSecurity(prePostEnabled = true,jsr250Enabled = true)
private static class GlobalSecurityConfiguration extends GlobalMethodSecurityConfiguration {
    @Override
    protected MethodSecurityExpressionHandler createExpressionHandler() {
        return new OAuth2MethodSecurityExpressionHandler();
    }

}

}

CustomAuthenticationEntryPoint.java

@Component
public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint {

private final Logger log = LoggerFactory.getLogger(CustomAuthenticationEntryPoint.class);

public void commence(HttpServletRequest request,HttpServletResponse response,AuthenticationException ae) throws IOException,servletexception {

    log.info("Pre-authenticated entry point called. Rejecting access");
    response.sendError(HttpServletResponse.SC_UNAUTHORIZED,"Access Denied");

}
}

我想要实现的是使用浏览器上的登录表单对用户进行身份验证以访问受保护的资源,但我不知道在此配置中如何。 例子 : 当我访问 /product 时,它会显示所有产品,因为它不安全,但是 /product/3 例如受到保护,因此它显示一个空白网页,错误访问被拒绝,我想显示登录表单。

什么时候

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。