Reputation: 445
Despite lot of subject, i cant figure out how to authenticate with my angular project to my back with spring boot so i try to post with my setup.
So far, all my authentification is handle by spring boot and work
@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;
}
}
i started a new angular project and try to bind it with angular-oauth2-oidc.
in 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,
};
in 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/'));
}
}
I dont understand how the authentication must be handle in this config.
Upvotes: 2
Views: 3081
Reputation: 6944
The annotation @EnableOAuth2Sso
transforms your spring application in an OAuth2 client
In your scenario, instead, you want that your application is a ResourceServer
So you should use the @EnableResourceServer
annotation.
Spring security should be configured like this:
@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;
}
}
On angular side I suggest to you to use angulat-oauth2-oidc plugin https://github.com/manfredsteyer/angular-oauth2-oidc
Upvotes: 1