Hej, robię projekt i postanowiłem zrobić logowanie na stronie, dodałem dependencje do pom'a której chciałem używać przy logowaniu, ale z jakiegoś powodu blokuje ona dostęp i najprostsze zapytanie GET nie chce przejść zwracając 401 Unauthorized, pomysły ?
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
Moje pozostałe klasy zawierjące konfiguracje bezpieczeństwa to:
JWTFilter
public class JWTFilter extends GenericFilterBean {
// private static final Logger logger =
public static final String AUTHORIZATION_HEADER = "Authorization";
public static final String AUTHORITIES_KEY = "roles";
public static final String SECRET = "mysecret";
public static final String BEARER= "Bearer ";
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
String authHeader = request.getHeader(AUTHORIZATION_HEADER);
System.out.println(authHeader);
if (authHeader == null || !authHeader.contains(BEARER)) {
HttpServletResponse response = (HttpServletResponse) servletResponse;
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Invalid Authorization header.");
} else {
// try {
//we'r logged in
String token= authHeader.substring(BEARER.length());
Claims claims = Jwts.parser().setSigningKey(SECRET).parseClaimsJws(token).getBody();
request.setAttribute("claims", claims);
SecurityContextHolder.getContext().setAuthentication(getAuthentication(claims));
//we pass the request and answer to filter chain
filterChain.doFilter(servletRequest, servletResponse);
// } catch (SignatureException eq) {
// ((HttpServletResponse) servletResponse).sendError(HttpServletResponse.SC_UNAUTHORIZED, "Invalid token.");
// }
}
}
private Authentication getAuthentication(Claims claims) {
List<SimpleGrantedAuthority> authorities = new ArrayList<>();
List<String> roles = (List<String>) claims.get(AUTHORITIES_KEY);
for (String role : roles) {
authorities.add(new SimpleGrantedAuthority(role));
}
User principal = new User(claims.getSubject(), "", authorities);
UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(
principal, "", authorities);
return usernamePasswordAuthenticationToken;
}
}
Security Configuration
@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Bean
public BCryptPasswordEncoder bCryptPasswordEncoder(){
return new BCryptPasswordEncoder();
}
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/auth/register","auth/authenticate");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors().and()
.csrf().disable()
.authorizeRequests()
.antMatchers(HttpMethod.POST, "/auth/register").permitAll()
.antMatchers(HttpMethod.POST,"/auth/authenticate").permitAll()
.anyRequest().fullyAuthenticated().and()
.addFilterBefore(new JWTFilter(),UsernamePasswordAuthenticationFilter.class)
.httpBasic().and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}
}
i AuthenticationController
@RestController
@CrossOrigin
@RequestMapping(path = "/auth")
public class AuthenticationController {
@Autowired
private UserService userService;
private static final Logger logger = Logger.getLogger(String.valueOf(AuthenticationController.class));
@RequestMapping(path = "/register", method = RequestMethod.POST)
public ResponseEntity register(@RequestBody AppUserRegisterDto dto) {
Optional<AppUserDto> user = userService.registerUser(dto);
if (user.isPresent()) {
return ResponseFactory.created(user.get());
}
return ResponseFactory.badRequest();
}
@RequestMapping(path = "/authenticatee", method = RequestMethod.POST)
public ResponseEntity authenticate2(@RequestBody LoginDto dto) {
return ResponseFactory.ok("hello");
}
@RequestMapping(path = "/authenticate", method = RequestMethod.POST)
public ResponseEntity authenticate(@RequestBody LoginDto loginDto) {
Optional<AppUser> appUserOptional = userService.getUserWithLoginAndPassword(loginDto);
if (appUserOptional.isPresent()) {
AppUser user = appUserOptional.get();
SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(SECRET);
Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());
String token = Jwts.builder()
.setSubject(user.getLogin()).setIssuedAt(new Date())
.claim("roles", translateRoles(user.getRoleSet()))
.signWith(signatureAlgorithm, signingKey)
.compact();
System.out.println(token);
// return ResponseFactory.ok(user);
return ResponseFactory.ok(new AuthenticationDto(user.getLogin(), user.getId(), token));
}
return ResponseFactory.badRequest();
}
private Set<String> translateRoles(Set<Role> roleSet) {
return roleSet.stream().map(role -> role.getName()).collect(Collectors.toSet());
}
}