如何使用Spring Boot将OAuth2身份验证与前端绑定

问题描述 投票:0回答:1

尽管主题很多,但我无法弄清楚如何用弹簧靴对我的棱角项目进行身份验证,因此我尝试将其设置发布。

到目前为止,我所有的身份验证都由Spring Boot和工作完成

@Configuration
@EnableOAuth2Sso
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .cors()
                .and()
                .csrf().disable()
                .authorizeRequests()

                .antMatchers("/", "/home").permitAll()
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .loginPage("/login")
                .permitAll()

                .and()
                .logout().clearAuthentication(true)
                .logoutSuccessUrl("/")
                .permitAll();

    }
    @Bean
    CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Arrays.asList("https://localhost:4200"));
        configuration.setAllowedMethods(Arrays.asList("GET","POST"));
        configuration.setAllowedHeaders(Arrays.asList("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"));
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }

}

我启动了一个新的角度项目,并尝试将其与angular-oauth2-oidc绑定。

在auth.config.js中

import { AuthConfig } from 'angular-oauth2-oidc';

export const authConfig: AuthConfig = {
  clientId: 'xxxxxx',
  issuer: 'https://accounts.google.com/',
  // loginUrl: 'http://localhost:8080',
  redirectUri: window.location.origin + '/user.html',
  scope: 'openid profile email',
  tokenEndpoint: 'https://www.googleapis.com/oauth2/v3/token',

  // strictDiscoveryDocumentValidation: false,
  userinfoEndpoint: 'http://localhost:8080/user',
  // disableAtHashCheck: true,

  // nonceStateSeparator: ',',

  // clearHashAfterLogin: false,
};

在login.component.ts中

import { Component, OnInit } from '@angular/core';
import { OAuthService, JwksValidationHandler } from 'angular-oauth2-oidc';
import { authConfig } from '../auth.config';



@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})

export class LoginComponent implements OnInit {
  constructor(private oauthService: OAuthService) {
    this.oauthService.configure(authConfig);
    this.oauthService.tokenValidationHandler = new JwksValidationHandler();
    this.oauthService.loadDiscoveryDocumentAndTryLogin();
  }
  ngOnInit() {
    this.oauthService.initImplicitFlow(encodeURIComponent('http://localhost8080/'));
  }

}

我不了解如何在此配置中处理身份验证。

java angular spring oauth-2.0 google-authentication
1个回答
1
投票

批注@EnableOAuth2Sso可以在OAuth2客户端中转换spring应用程序

相反,在您的方案中,您希望您的应用程序是ResourceServer因此应使用@EnableResourceServer批注。

Spring安全性应配置如下:

@Configuration
@EnableWebSecurity
@EnableResourceServer
@PropertySource(value = { "classpath:application.properties" }, encoding = "UTF-8", ignoreResourceNotFound = false)
public class OAuth2ResourceServerConfig extends ResourceServerConfigurerAdapter {

    @Autowired
    private Environment env;

    @Override
    public void configure(final HttpSecurity http) throws Exception {
        http
        .sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
        .and()
            .authorizeRequests()
            .antMatchers("/swagger-ui.html","/webjars/**","/swagger-resources/**", "/v2/**","/csrf")
            .permitAll()
            .antMatchers("/**")
            .authenticated()
        .and()
            .cors()
            .configurationSource(corsConfigurationSource())
        .and()
            .exceptionHandling()
            .accessDeniedHandler(new OAuth2AccessDeniedHandler());
    }

    @Override
    public void configure(final ResourceServerSecurityConfigurer config) {
        config
        .tokenServices(tokenServices())
        .resourceId("RES_ID");
    }

    @Bean
    @Primary
    public DefaultTokenServices tokenServices() {
        final DefaultTokenServices tokenServices = new DefaultTokenServices();
        tokenServices.setTokenStore(tokenStore());
        return tokenServices;
    }

    @Bean
    public TokenStore tokenStore()
    {
        JwkTokenStore result = new JwkTokenStore("JWTKS_URL", accessTokenConverter());
        return result;
    }

    @Bean
    public JwtAccessTokenConverter accessTokenConverter()
    {
        final JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
        converter.setAccessTokenConverter(new  DefaultAccessTokenConverter() {
            @Override
            public OAuth2Authentication extractAuthentication(Map<String, ?> map) {
                final OAuth2Authentication auth = super.extractAuthentication(map);
                auth.setDetails(map);
                return auth;
            }
        });
        return converter;
    }

    @Bean
    public JwtClaimsSetVerifier jwtClaimsSetVerifier() {
        return new DelegatingJwtClaimsSetVerifier(Arrays.asList(issuerClaimVerifier(), customJwtClaimVerifier()));
    }

    @Bean
    public JwtClaimsSetVerifier issuerClaimVerifier() {
        try {
            return new IssuerClaimVerifier(new URL("ISSUER CLAIMS URL"));
        } catch (final MalformedURLException e) {
            throw new RuntimeException(e);
        }
    }

    @Bean
    public JwtClaimsSetVerifier customJwtClaimVerifier() {
        return new CustomClaimVerifier();
    }



    @Bean
    CorsConfigurationSource corsConfigurationSource() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();

        boolean abilitaCors = new Boolean(env.getProperty("profile.manager.web.cors.enbaled"));
        if( abilitaCors )
        {

            CorsConfiguration configuration = new CorsConfiguration();
            configuration.setAllowCredentials(true);
            configuration.addAllowedOrigin("*");
            configuration.addAllowedHeader("*");
            configuration.addAllowedMethod("*");
            configuration.setExposedHeaders(Arrays.asList("X-Auth-Token","x-auth-token", "x-requested-with", "x-xsrf-token","Access-Control-Allow-Origin", "content-type"));
            source.registerCorsConfiguration("/**", configuration);
        }
        return source;
    }
}

在角度方面,我建议您使用angulat-oauth2-oidc插件https://github.com/manfredsteyer/angular-oauth2-oidc

© www.soinside.com 2019 - 2024. All rights reserved.