Im using Java, Spring and Spring Security (latest version of them and no SpringBoot application) for Back-End and AngularJS for Front-End. I require to generate a JWT to authorize the acces to some endpoints in my project. The thing is when I generate the token everything goes fine, but when I try to acces to an endpoint wich needs authorization it sends me the error 401 (as expected) even though I send the token on the headers (using postman makes the same thing about the 401 error). My thoughts are that I’m missing some sort of Manager authentication where the project doesnt recognize the token I’m sending.
Here are some files that I use to make sure that Spring Security works properly and generate the token.
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/appServlet-servlet.xml</param-value>
</context-param>
<servlet>
<servlet-name>appServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>appServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<filter>
<filter-name>cors</filter-name>
<filter-class>com.mx.xpertys.CORSFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>cors</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- Spring Security -->
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- -->
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
</web-app>
JwtUtils.java:
package com.mx.xpertys.security.config;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;
import java.security.Key;
import java.time.Instant;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
public class JwtUtils {
private static final Key SECRET_KEY = Keys.secretKeyFor(io.jsonwebtoken.SignatureAlgorithm.HS256);
public static String generateToken(String username, String password, long expirationSeconds) {
Instant now = Instant.now();
Instant expiration = now.plusSeconds(expirationSeconds);
Map<String, Object> claims = new HashMap<>();
claims.put("username", username);
claims.put("password", password);
return Jwts.builder()
.setClaims(claims)
.setIssuedAt(Date.from(now))
.setExpiration(Date.from(expiration))
.signWith(SECRET_KEY)
.compact();
}
}
SecurityConfig.Java
package com.mx.xpertys.security.config;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.util.UUID;
import com.nimbusds.jose.jwk.JWKSet;
import com.nimbusds.jose.jwk.RSAKey;
import com.nimbusds.jose.jwk.source.ImmutableJWKSet;
import com.nimbusds.jose.jwk.source.JWKSource;
import com.nimbusds.jose.proc.SecurityContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.security.oauth2.core.ClientAuthenticationMethod;
import org.springframework.security.oauth2.core.oidc.OidcScopes;
import org.springframework.security.oauth2.jwt.JwtDecoder;
import org.springframework.security.oauth2.server.authorization.client.InMemoryRegisteredClientRepository;
import org.springframework.security.oauth2.server.authorization.client.RegisteredClient;
import org.springframework.security.oauth2.server.authorization.client.RegisteredClientRepository;
import org.springframework.security.oauth2.server.authorization.config.annotation.web.configuration.OAuth2AuthorizationServerConfiguration;
import org.springframework.security.oauth2.server.authorization.config.annotation.web.configurers.OAuth2AuthorizationServerConfigurer;
import org.springframework.security.oauth2.server.authorization.settings.AuthorizationServerSettings;
import org.springframework.security.oauth2.server.authorization.settings.ClientSettings;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint;
import org.springframework.security.web.util.matcher.MediaTypeRequestMatcher;
/**
*
* @author Diego
*/
@Configuration
@EnableWebSecurity
public class SecurityConfig{
public SecurityConfig() {
System.out.println("Entró al SecurityConfig");
}
@Bean
@Order(2)
public SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception {
System.out.println("Entro al segundo");
OAuth2AuthorizationServerConfiguration.applyDefaultSecurity(http);
http.getConfigurer(OAuth2AuthorizationServerConfigurer.class)
.oidc(Customizer.withDefaults());
http
.exceptionHandling((exceptions) -> exceptions
.defaultAuthenticationEntryPointFor(
new LoginUrlAuthenticationEntryPoint("/login"),
new MediaTypeRequestMatcher(MediaType.TEXT_HTML)
)
)
// Accept access tokens for User Info and/or Client Registration
.oauth2ResourceServer((resourceServer) -> resourceServer
.jwt(Customizer.withDefaults()));
return http.build();
}
@Bean
@Order(1)
public SecurityFilterChain defaultSecurityFilterChain(HttpSecurity http) throws Exception {
http.authorizeHttpRequests((authorize) -> {
authorize.requestMatchers(HttpMethod.GET, "/hola", "/adios", "/generarToken").permitAll()
.requestMatchers(HttpMethod.POST, "/consulta/**").permitAll()
.requestMatchers(HttpMethod.GET, "/seguridad").authenticated()
.anyRequest().authenticated();
}).csrf(csrf -> csrf.disable())
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.oauth2ResourceServer(resourceServer -> resourceServer.jwt(Customizer.withDefaults()));
System.out.println("Pasó el filtro de SecurityConfig");
return http.build();
}
@Bean
public UserDetailsService userDetailsService() {
UserDetails userDetails = User.builder()
.username("diego")
.password("hola")
.roles("USER")
.build();
return new InMemoryUserDetailsManager(userDetails);
}
@Bean
public RegisteredClientRepository registeredClientRepository() {
RegisteredClient oidcClient = RegisteredClient.withId(UUID.randomUUID().toString())
.clientId("oidc-client")
.clientSecret("{noop}secret")
.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC)
.authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
.authorizationGrantType(AuthorizationGrantType.REFRESH_TOKEN)
.redirectUri("http://127.0.0.1:8080/login/oauth2/code/oidc-client")
.postLogoutRedirectUri("http://127.0.0.1:8080/")
.scope(OidcScopes.OPENID)
.scope(OidcScopes.PROFILE)
.clientSettings(ClientSettings.builder().requireAuthorizationConsent(false).build())
.build();
return new InMemoryRegisteredClientRepository(oidcClient);
}
@Bean
public JWKSource<SecurityContext> jwkSource() {
KeyPair keyPair = generateRsaKey();
RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
RSAKey rsaKey = new RSAKey.Builder(publicKey)
.privateKey(privateKey)
.keyID(UUID.randomUUID().toString())
.build();
JWKSet jwkSet = new JWKSet(rsaKey);
return new ImmutableJWKSet<>(jwkSet);
}
private static KeyPair generateRsaKey() {
KeyPair keyPair;
try {
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(2048);
keyPair = keyPairGenerator.generateKeyPair();
}
catch (Exception ex) {
throw new IllegalStateException(ex);
}
return keyPair;
}
@Bean
public JwtDecoder jwtDecoder(JWKSource<SecurityContext> jwkSource) {
return OAuth2AuthorizationServerConfiguration.jwtDecoder(jwkSource);
}
@Bean
public AuthorizationServerSettings authorizationServerSettings() {
return AuthorizationServerSettings.builder().build();
}
}
Prueba.java:
package com.mx.xpertys;
import com.mx.xpertys.security.config.*;
import java.util.HashMap;
import java.util.Map;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class Prueba {
@GetMapping(value = "/hola")
public String hola() {
return "Hola";
}
@GetMapping(value = "/adios")
public String adios() {
int min = 20, max = 80;
return String.valueOf(Math.clamp(100, min, max)); //clamp es un método que se incorporó en la verisón 21 de Java
}
@GetMapping(value = "/seguridad")
public String seguridad(@RequestHeader("x-xsrf-token") String token) {
return "Exito. Token: " + token;
}
@GetMapping(value = "/generarToken")
public ResponseEntity<Map<String, String>> generarToken(@RequestParam("username") String username, @RequestParam("password") String password) {
String token = JwtUtils.generateToken(username, password, 3600);
// Se devuelve el token en una respuesta JSON
Map<String, String> response = new HashMap<>();
response.put("token", token);
return ResponseEntity.ok(response);
}
}
As you can see, the method generarToken() in Prueba.Java is the one who generate the token (because thats the endpoint I call from the Front-End); and I want to reach the endpoint seguridad but I can´t acces to it because the defaultSecurityFilterChain of the file SecurityConfig is not working as I expected (I think its blocking it). Do I need to implement something else? Or need to change the configuration of SecurityConfig file?
BTW I made sure that the file SecurityConfig is enable by printing some lines on the logs. And it seems to be succesfully accepted.
enter image description here
Diego Becerril is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.