Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/28.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-mvc/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何将angular front与oauth2绑定使用spring boot进行身份验证_Java_Angular_Spring_Oauth 2.0_Google Authentication - Fatal编程技术网

Java 如何将angular front与oauth2绑定使用spring boot进行身份验证

Java 如何将angular front与oauth2绑定使用spring boot进行身份验证,java,angular,spring,oauth-2.0,google-authentication,Java,Angular,Spring,Oauth 2.0,Google Authentication,尽管主题很多,但我不知道如何用spring boot验证我背部的angular项目,所以我尝试发布我的设置 到目前为止,我所有的身份验证都由spring引导和工作来处理 @Configuration @EnableOAuth2Sso public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurit

尽管主题很多,但我不知道如何用spring boot验证我背部的angular项目,所以我尝试发布我的设置

到目前为止,我所有的身份验证都由spring引导和工作来处理

@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项目,并尝试将其与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/'));
  }

}

我不明白在这个配置中必须如何处理身份验证。

注释
@enableAuth2sso
在OAuth2客户端中转换您的spring应用程序

相反,在您的场景中,您希望您的应用程序是一个
ResourceServer
因此,您应该使用
@EnableResourceServer
注释

Spring security的配置应如下所示:

@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;
    }
}
@配置
@启用Web安全性
@EnableResourceServer
@PropertySource(值={“classpath:application.properties”},encoding=“UTF-8”,ignoreResourceNotFound=false)
公共类OAuth2ResourceServerConfig扩展了ResourceServerConfigurerAdapter{
@自动连线
私人环境署;
@凌驾
public void configure(最终HttpSecurity http)引发异常{
http
.会议管理()
.sessionCreationPolicy(sessionCreationPolicy.STATELESS)
.及()
.授权请求()
.antMatchers(“/swagger ui.html”、“/webjars/**”、“/swagger resources/**”、“/v2/**”、“/csrf”)
.permitAll()
.antMatchers(“/**”)
.authenticated()
.及()
.cors()
.configurationSource(CORSCOConfiguration源())
.及()
.例外处理()
.accessDeniedHandler(新的OAuth2AccessDeniedHandler());
}
@凌驾
public void配置(最终资源服务器安全配置器配置){
配置
.tokenServices(tokenServices())
.资源ID(“资源ID”);
}
@豆子
@初级的
公共DefaultTokenServices令牌服务(){
final DefaultTokenServices tokenServices=新的DefaultTokenServices();
setTokenStore(tokenStore());
退货服务;
}
@豆子
公共令牌库令牌库()
{
JwkTokenStore result=newjwktokenstore(“JWTKS_URL”,accessTokenConverter());
返回结果;
}
@豆子
公共JwtAccessTokenConverter accessTokenConverter()
{
最终JwtAccessTokenConverter=新JwtAccessTokenConverter();
setAccessTokenConverter(新的DefaultAccessTokenConverter(){
@凌驾
公共OAuth2Authentication extractAuthentication(映射){
最终OAuth2Authentication auth=super.extractAuthentication(map);
授权设置详细信息(地图);
返回auth;
}
});
回流转换器;
}
@豆子
公共jwtclaimsetverifier jwtclaimsetverifier(){
返回新的DelegatingJwtClaimsSetVerifier(Arrays.asList(issuerClaimVerifier(),customJwtClaimVerifier());
}
@豆子
公共JwtClaimsSetVerifier发行人ClaimVerifier(){
试一试{
返回新的发行人索赔验证人(新URL(“发行人索赔URL”);
}捕获(最终格式错误){
抛出新的运行时异常(e);
}
}
@豆子
公共JWTclaimsetVerifier customJwtClaimVerifier(){
返回新的CustomClaimVerifier();
}
@豆子
CorsConfiguration源CorsConfiguration源(){
UrlBasedCorsConfigurationSource=新的UrlBasedCorsConfigurationSource();
boolean-abilitaCors=new-boolean(env.getProperty(“profile.manager.web.cors.enbaled”);
如果(abilitaCors)
{
CorsConfiguration配置=新的CorsConfiguration();
配置.setAllowCredentials(true);
配置。addAllowedOrigin(“*”);
configuration.addAllowedHeader(“*”);
configuration.addAllowedMethod(“*”);
configuration.setExposedHeaders(Arrays.asList(“X-Auth-Token”、“X-Auth-Token”、“X-request-with”、“X-xsrf-Token”、“访问控制允许源”、“内容类型”);
source.registerCorsConfiguration(“/**”,配置);
}
返回源;
}
}

在角度方面,我建议您使用angulat-oauth2-oidc插件

thx我会尽快尝试,有两件事,我的aungular outh2 oidc配置OK键吗?发行人应该是我的ServeurSpring还是google?使用ouath2 oidc插件,我在discoverydocument中获得了无效的颁发者,预期为:current:。颁发者和JWTKS所有者是您案例中的google授权服务器。关于您的oidc配置,我似乎陷入了vue上的身份验证循环中。在谷歌上试用后,我被重定向到另一个试用