Spring Oauth2 + Spring Security

Java

16/10/2017

Estou desenvolvendo uma aplicação que tem uma interface web, e uma camada Rest, essa camada Rest vai usar Oauth2, e o restante, vai se autenticar usando um formulário de login e senha.

O problema, é que a configuração de Security do spring esta sobrescrevendo minhas configurações do ResourceServer, eu consigo autenticar normalmente no AuthorizationServer, mas quando tento acessar alguma url Rest com o token gerado, ele me redireciona para o formulário de login.

Depois de pesquisar muito eu consegui fazer com que não redirecionasse mais para o formulário, mas ele não autentica com o Token, e retorna erro 403.

É possível manter as duas formas de autenticação, e filtrar por url qual vai se autenticar via token, e qual vai se autenticar através do formulário de login?

Segue abaixo minha configuração de segurança.

@Configuration
@EnableAuthorizationServer
@EnableWebSecurity
public class OAuth2Config extends AuthorizationServerConfigurerAdapter {
	private static final String RESOURCE_ID = "resource_id";
	@Autowired
	private CustomUserDetailsService userDetailsService;

	@Autowired
	private AuthenticationManager authenticationManager;

	@Value("${oauth.tokenTimeout:3600}")
	private int expiration;

	@Bean
	public PasswordEncoder passwordEncoder() {
		return new BCryptPasswordEncoder();
	}

	@Override
	public void configure(AuthorizationServerEndpointsConfigurer configurer) throws Exception {
		configurer.authenticationManager(authenticationManager);
		configurer.userDetailsService(userDetailsService);
	}

	@Override
	public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
		oauthServer.allowFormAuthenticationForClients(); // Disable /oauth/token Http Basic Auth
		oauthServer.tokenKeyAccess("permitAll()").checkTokenAccess("isAuthenticated()");
	}	
	
	@Override
	public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
		clients
			.inMemory()
			.withClient("client_id")
			.authorizedGrantTypes("password", "refresh_token")
			.authorities("ADMIN")
			.scopes("read", "write")
			.resourceIds(RESOURCE_ID)
			.secret("senha")
			.accessTokenValiditySeconds(expiration);
	}
}

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter{

    @Configuration
    @Order(1)
    public static class ApiWebSecurityConfig extends WebSecurityConfigurerAdapter{
 	
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.csrf().disable() 
            .antMatcher("/api/**")
            .authorizeRequests()
            .anyRequest().hasAnyRole("ADMIN", "USER", "AGENTE")
            .antMatchers("/api/**").fullyAuthenticated()
            .and()
            .httpBasic().disable();
        }
    }

    @Configuration
    @Order(2)
    public static class FormWebSecurityConfig extends WebSecurityConfigurerAdapter{

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

        @Override
        public void configure(WebSecurity web) throws Exception {
    		web.ignoring().antMatchers("/static/**");
    		web.ignoring().antMatchers("/webjars/**");
    		web.ignoring().antMatchers("/upload/**");
        }

        @Override
        protected void configure(HttpSecurity http) throws Exception {
            //Permissões
      		http
      		.authorizeRequests()
      		.antMatchers("/usuario/**").hasRole("ADMIN")
      		.antMatchers("/relatorio/**").hasAnyRole("ADMIN","USER")
      		.anyRequest().authenticated();
            
    		//Login
    		http.formLogin()
    		.loginPage("/login")
    		.permitAll()
    		.defaultSuccessUrl("/", false)
    		.failureUrl("/error-login")
    		.usernameParameter("login")
    		.passwordParameter("password");
    		
    		//Logout
    		http.logout()
    		.logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
    		.logoutSuccessUrl("/login")
    		.permitAll();
    				
    		//Remenber-me
    		http.rememberMe()
    		.tokenValiditySeconds(1209600);
        }
    }
}

@EnableResourceServer
@Configuration
public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter{
	private static final String RESOURCE_ID = "floricultura-service";
	
	@Autowired
	private JsonToUrlEncodedAuthenticationFilter jsonFilter;
	
	@Override
    public void configure(ResourceServerSecurityConfigurer resources) {
        resources.resourceId(RESOURCE_ID).stateless(false);
    }
	
	@Override
    public void configure(HttpSecurity http) throws Exception {
		http.addFilterBefore(jsonFilter, ChannelProcessingFilter.class)
		.requestMatchers().antMatchers("/api/**")
        .and().authorizeRequests().anyRequest().authenticated();

		http.headers().contentTypeOptions().disable();
    }
}
Luis Sena

Luis Sena

Curtidas 0

Mais Respostas

Jone

Jone

16/10/2017

Buy Driver's License, Passport, ((wottenkelly79@gmail.com)) ((whatsapp +237679499813)))id card,Birth Certificate and Other

Documents ((wottenkelly79@gmail.com))))
We offer driving license, ID cards, Passports, Visas, marriage certificates,

baptism cards, diplomas of all kinds for sale ,


Obtain Registered Ielts,Toefl & Gre Certificat((wottenkelly79@gmail.com))))


We produce high quality genuine passports, driving license, ID card .Database

registered and unregistered. All documents are registered in the respective

government databases. Also we offer the following card: social security numbers,

credit files and credit cards, school diplomas, grades all in a completely new name

issued and registered in the database system of government. . We use high

quality equipment and materials to produce genuine and false documents. All

secret features of these documents are carefully duplicated for our documents.

We are the only producer of quality fake and registered documents. We offer only

original high-quality registered and unregistered passports, drivers licenses,

identification cards, stamps, Visa, school Securities and other products for a

number of countries such as USA, Australia, Belgium, Brazil, Canada, Italy, Finland

France, Germany, Israel, Mexico, Netherlands, South Africa, Spain, UK and many

more countries

CONTACT

General Support: <<<<<<<<<<<<<((wottenkelly79@gmail.com))))
Contact <<<<<<<<<<<<<<<<, +237679499813
Skype >>>>>>>>>> fastdocuments1

UNIVERSAL PAPERS

WE ARE ABLE TO PRODUCE PASSPORTS, DRIVER'S LICENSE, ID CARD AND ALL OTHER DOCUMENTS FOR THE FOLLOWING COUNTRIES

SPAIN
ENGLAND
ITALY
RUSSIA
USA
CANADA
BRAZIL
FRANCE
NETHERLANDS
SWEDEN
NORWAY
BELGIUM
CROATIA
AUSTRIA
BULGARIA
DENMARK
FINLAND
GERMANY
GEORGIA
HUNGARY
ICELAND
IRELAND
LITHAUNIA
LATVIA
POLAND
PORTUGAL
ROMANIA
SWITZERLAND
AUSTRALIA
SOUTH AMERICA COUNTRIES


General Support: >>>>>>>>>> ((wottenkelly79@gmail.com))))

Support >>>>>>>>>>>>>>((wottenkelly79@gmail.com))))

Contact >>>>>>>>>> +237679499813
Skype >>>>>>>>>>fastdocuments1

Registered and unregistered passport . visas all, biometric passports, degrees,

driver's license, ID certificates cards.Training M GCSE, A-levels, high school

diploma Certificates, GMAT, MCAT and LSAT examination certificates,

marriage and death certificates, passports and new identity packages, replicated,

Real Degrees / Diplomas of most higher education institutions around the world

(with more than 4000 templates in the file) all designed to look 100% identical to

original. Custom printing (if we do not have the template file - just email us back

and we can make any alterations / modifications as

addresses) .SECOND, citizenship, identity, identification documents, diplomatic,

Our workers are former private investigators, consulates, senior government staff

and experienced experts with experience, we have strong connections with


higher personnel in all areas of property registration documents and passports in

exchange for these countries They are linked to the passport agency in each of

these countries and with the help of his connections to all our customers who

require a document or passport countries are 100% safe and guaranteed receipt

of very high quality genuine estate documents recorded that can not be identified

as false !! Not even a custom official experience or machine never dictate false

document since the document is no different than real government issued! All our

documents Registered real genuine citizenship data bases have their personal

data recorded in the database system and 100% readable machine. Feel free to

get detailed information about our services.
GOSTEI 0
POSTAR