GUJ Discussões   :   últimos tópicos   |   categorias   |   GUJ Respostas

[RESOLVIDO] Endereço de login não precisa passar token


#1

WebSecurityConfig

package br.eti.netsoft.authSeguranca.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import br.eti.netsoft.authSeguranca.jwt.JwtAuthenticationEntryPoint;
import br.eti.netsoft.authSeguranca.jwt.JwtAuthenticationTokenFilter;
import br.eti.netsoft.authSeguranca.jwt.JwtTokenUtil;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

	@Autowired
	private JwtAuthenticationEntryPoint unauthorizedHandler;

	@Autowired
	private UserDetailsService userDetailsService;

	@Autowired
	private JwtTokenUtil jwtTokenUtil;

	@Value("Authorization")
	private String tokenHeader;

	@Autowired
	public void configureAuthentication(
			AuthenticationManagerBuilder authenticationManagerBuilder)
			throws Exception {
		authenticationManagerBuilder
				.userDetailsService(this.userDetailsService).passwordEncoder(
						passwordEncoder());
	}

	@Override
	protected void configure(HttpSecurity httpSecurity) throws Exception {
		httpSecurity
				.csrf()
				.disable()
				.exceptionHandling()
				.authenticationEntryPoint(unauthorizedHandler)
				.and()
				.sessionManagement()
				.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
				.and()
				.authorizeRequests()
				.antMatchers(HttpMethod.GET, "/", "/*.html", "/favicon.ico",
						"/**/*.html", "/**/*.css", "/**/*.js", "/login")
				.permitAll().antMatchers("/admin/**").permitAll().anyRequest()
				.authenticated();
		JwtAuthenticationTokenFilter authenticationTokenFilter = new JwtAuthenticationTokenFilter(
				userDetailsService(), jwtTokenUtil, tokenHeader);
		httpSecurity.addFilterBefore(authenticationTokenFilter,
				UsernamePasswordAuthenticationFilter.class);
		httpSecurity.headers().cacheControl();
	}

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

	@Bean
	public CorsConfigurationSource corsConfigurationSource() {
		CorsConfiguration configuration = new CorsConfiguration();
		configuration.setAllowCredentials(true);
		configuration.addAllowedOrigin("*");
		configuration.addAllowedHeader("*");
		configuration.addAllowedMethod("*");
		UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
		source.registerCorsConfiguration("/admin/**", configuration);
		return source;
	}

	@Bean
	public AuthenticationManager customAuthenticationManager() throws Exception {
		return authenticationManager();
	}
}

JwtAuthenticationTokenFilter

package br.eti.netsoft.authSeguranca.jwt;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.web.filter.OncePerRequestFilter;

public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

	private static final String USUARIO_NAO_ENCONTRADO = "Usuário não encontrado.";
	private static final String CONTEXTO_SEGURANCA_SISTEMA_AUTH_SEGURANCA_TOKEN = ", contexto de segurança do sistema: AUTH SEGURANÇA. Token: ";
	private static final String USUARIO_AUTENTICADO = "Usuário autenticado ";
	private static final String AUTHORIZATION = "Authorization";
	private UserDetailsService userDetailsService;
	private JwtTokenUtil jwtTokenUtil;
	private String tokenHeader;

	public JwtAuthenticationTokenFilter(UserDetailsService userDetailsService,
			JwtTokenUtil jwtTokenUtil, String tokenHeader) {
		this.userDetailsService = userDetailsService;
		this.jwtTokenUtil = jwtTokenUtil;
		this.tokenHeader = tokenHeader;
	}

	protected void doFilterInternal(HttpServletRequest request,
			HttpServletResponse response, FilterChain chain)
			throws ServletException, IOException {
		String authToken = request.getHeader(AUTHORIZATION);
		String username = jwtTokenUtil.getUsernameFromToken(authToken);
		if (username != null
				&& SecurityContextHolder.getContext().getAuthentication() == null) {
			UserDetails userDetails = this.userDetailsService
					.loadUserByUsername(username);
			if (jwtTokenUtil.validateToken(authToken, userDetails)) {
				UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
						userDetails, null, userDetails.getAuthorities());
				authentication.setDetails(new WebAuthenticationDetailsSource()
						.buildDetails(request));
				logger.info(USUARIO_AUTENTICADO + username
						+ CONTEXTO_SEGURANCA_SISTEMA_AUTH_SEGURANCA_TOKEN
						+ tokenHeader);
				SecurityContextHolder.getContext().setAuthentication(
						authentication);
			}
		} else {
			logger.info(USUARIO_NAO_ENCONTRADO);
		}
		chain.doFilter(request, response);
	}
}

controller

@PostMapping(value = "/login", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public ResponseEntity<?> createAuthenticationToken(
			@RequestBody JwtAuthenticationRequest authenticationRequest){

}

Para eu acessar o /login, devo passar um token válido, se não dá página não autorizada.

Imagens em anexo

Marcando

Não marcando

O que devo fazer ?


#2

acho q vc precisa permitir também POST no /login

vc faz

antMatchers(HttpMethod.GET, "/", "/*.html", "/favicon.ico",
						"/**/*.html", "/**/*.css", "/**/*.js", "/login")

logo, parece q vc pode fazer também

antMatchers(HttpMethod.POST, "/login")

#3

Obrigado e funcionou