Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- @Configuration
- @EnableAuthorizationServer
- public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
- static final String CLIEN_ID = "goodEApp-client";
- static final String CLIENT_SECRET = "goodEApp-secret";
- static final String GRANT_TYPE_PASSWORD = "password";
- static final String AUTHORIZATION_CODE = "authorization_code";
- static final String REFRESH_TOKEN = "refresh_token";
- static final String IMPLICIT = "implicit";
- static final String SCOPE_READ = "read";
- static final String SCOPE_WRITE = "write";
- static final String TRUST = "trust";
- static final int ACCESS_TOKEN_VALIDITY_SECONDS = 1*60*60;
- static final int FREFRESH_TOKEN_VALIDITY_SECONDS = 6*60*60;
- @Autowired
- private AuthenticationManager authenticationManager;
- @Bean
- public JwtAccessTokenConverter accessTokenConverter() {
- JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
- converter.setSigningKey("as466gf");
- return converter;
- }
- @Bean
- public TokenStore tokenStore() {
- return new JwtTokenStore(accessTokenConverter());
- }
- @Override
- public void configure(ClientDetailsServiceConfigurer configurer) throws Exception {
- configurer
- .inMemory()
- .withClient(CLIEN_ID)
- .secret(new BCryptPasswordEncoder().encode(CLIENT_SECRET))
- .authorizedGrantTypes(GRANT_TYPE_PASSWORD, AUTHORIZATION_CODE, REFRESH_TOKEN, IMPLICIT )
- .scopes(SCOPE_READ, SCOPE_WRITE, TRUST)
- .accessTokenValiditySeconds(ACCESS_TOKEN_VALIDITY_SECONDS).
- refreshTokenValiditySeconds(FREFRESH_TOKEN_VALIDITY_SECONDS);
- }
- @Override
- public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
- endpoints.tokenStore(tokenStore())
- .authenticationManager(authenticationManager)
- .accessTokenConverter(accessTokenConverter());
- }
- }
- @Configuration
- @EnableResourceServer
- public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
- private static final String RESOURCE_ID = "resource_id";
- @Override
- public void configure(ResourceServerSecurityConfigurer resources) {
- resources.resourceId(RESOURCE_ID).stateless(false);
- }
- @Override
- public void configure(HttpSecurity http) throws Exception {
- http
- .anonymous().disable()
- .authorizeRequests()
- .antMatchers("/resources/**").permitAll()
- .and().exceptionHandling().accessDeniedHandler(new OAuth2AccessDeniedHandler());
- }
- }
- @Configuration
- @EnableWebSecurity
- @EnableGlobalMethodSecurity(prePostEnabled = true)
- public class SecurityConfig extends WebSecurityConfigurerAdapter {
- @Autowired
- private DataSource dataSource;
- @Override
- @Bean
- public AuthenticationManager authenticationManagerBean() throws Exception {
- return super.authenticationManagerBean();
- }
- @Bean
- public BCryptPasswordEncoder bCryptPasswordEncoder() {
- return new BCryptPasswordEncoder();
- }
- @Autowired
- public void globalUserDetails(AuthenticationManagerBuilder auth) throws Exception {
- auth.jdbcAuthentication().dataSource(dataSource)
- .usersByUsernameQuery("select username, password, enabled "
- + " from accounts where username=?")
- .authoritiesByUsernameQuery("select a.username, r.role "
- + "from accounts a, access_roles r "
- + "where a.username=? and a.id_access_role = r.id_access_role")
- .passwordEncoder(bCryptPasswordEncoder());
- }
- @Override
- protected void configure(HttpSecurity http) throws Exception {
- http
- .csrf().disable()
- .anonymous().disable()
- .authorizeRequests()
- .antMatchers("/resources/**").permitAll()
- .and().exceptionHandling().authenticationEntryPoint(new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED));
- }
- @Bean
- public FilterRegistrationBean corsFilter() {
- UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
- CorsConfiguration config = new CorsConfiguration();
- config.setAllowCredentials(true);
- config.addAllowedOrigin("*");
- config.addAllowedHeader("*");
- config.addAllowedMethod("*");
- source.registerCorsConfiguration("/**", config);
- FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
- bean.setOrder(0);
- return bean;
- }
- }
- @Injectable()
- export class AccountService {
- constructor(private http: HttpClient) {
- }
- private baseUri = '//localhost:8081/account';
- private tokenUri = '//localhost:8081/oauth/token';
- public getLoginToken(usernameCli: string, passwordCli: string) {
- let headers_object = new HttpHeaders();
- headers_object.append('Content-Type', 'application/x-www-form-urlencoded');
- headers_object.append("Authorization", "Basic " + btoa("goodEApp-client:goodEApp-secret"));
- const httpOptions = {
- headers: headers_object
- };
- const credentials = {username: usernameCli, password: passwordCli, grant_type: "password"};
- return this.http.post<any>(this.tokenUri, credentials, httpOptions);
- }
- public getLoggedAccount(){
- return this.http.get<Account>(this.baseUri + "/getLoggedAccount")
- }
- }
- @Component({
- selector: 'app-login',
- templateUrl: './login.component.html',
- styleUrls: ['./login.component.scss']
- })
- export class LoginComponent implements OnInit {
- loginForm: FormGroup;
- loading = false;
- submitted = false;
- error = '';
- constructor(
- private formBuilder: FormBuilder,
- private router: Router,
- private accountService: AccountService) {}
- ngOnInit() {
- this.loginForm = this.formBuilder.group({
- username: ['', Validators.required],
- password: ['', Validators.required]
- });
- }
- get f() { return this.loginForm.controls; }
- onSubmit() {
- this.submitted = true;
- // stop here if form is invalid
- if (this.loginForm.invalid) {
- return;
- }
- this.loading = true;
- this.accountService.getLoginToken(this.f.username.value, this.f.password.value)
- .pipe(first())
- .subscribe(
- data => {
- console.log(data.toString());
- },
- error => {
- this.error = error.toString();
- this.loading = false;
- });
- }
- }
- @Override
- public void configure(WebSecurity web) throws Exception {
- web.ignoring().antMatchers(HttpMethod.OPTIONS);
- }
- @Configuration
- public class CorsConfig {
- @Bean
- public FilterRegistrationBean corsFilterRegistrationBean() {
- UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
- CorsConfiguration config = new CorsConfiguration();
- config.applyPermitDefaultValues();
- config.setAllowCredentials(true);
- config.setAllowedOrigins(Arrays.asList("*"));
- config.setAllowedHeaders(Arrays.asList("*"));
- config.setAllowedMethods(Arrays.asList("*"));
- config.setExposedHeaders(Arrays.asList("content-length"));
- config.setMaxAge(3600L);
- source.registerCorsConfiguration("/**", config);
- FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
- bean.setOrder(0);
- return bean;
- }
- }
- @Override
- protected void configure(HttpSecurity http) throws Exception {
- http
- .authorizeRequests()
- .antMatchers(HttpMethod.OPTIONS, "/oauth/token").permitAll()
- }
- @EnableWebSecurity
- class SecurityConfig extends WebSecurityConfigurerAdapter {
- CorsConfigurationSource corsConfigurationSource = new CorsConfigurationSource() {
- @Override
- public CorsConfiguration getCorsConfiguration(HttpServletRequest request) {
- CorsConfiguration corsConfiguration = new CorsConfiguration();
- corsConfiguration.addAllowedOrigin("http://localhost:63342");
- corsConfiguration.addAllowedHeader("Authorization");
- corsConfiguration.setAllowedMethods(Arrays.asList("POST", "GET"));
- corsConfiguration.setMaxAge(3600L);
- return corsConfiguration;
- }
- };
- .and().cors().configurationSource(corsConfigurationSource);
Add Comment
Please, Sign In to add comment