Spring oauth2 Local and external token generation - spring

I am planning to secure my REST server with external Identity provider(WSo2) or local spring ouath token generator. Token generation mode(Eternal/Internal) will be made configurable. I took the example listed below and modified the CORSFilter class to verify token with External provider(WSO2). I am not sure how to skip the local token generation and access my resource server here. I guess the authorization and Resource server needs to be separate module to achieve what I need.I am completely new to spring ouath so not sure if this is the right way. I tried all over the internet to find better example but not able to get one. Any pointers/examples will be helpful.
URL(example): http://websystique.com/spring-security/secure-spring-rest-api-using-oauth2/
public class CORSFilter extends OncePerRequestFilter {
private final Logger LOG = LoggerFactory.getLogger(CORSFilter.class);
#Override
protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res, FilterChain chain) throws ServletException, IOException {
//Read the keygen mode if it is External validation do this else skip all this so that local token is generated.
LOG.info("###token is"+ req.getHeader("Authorization"));
String token = req.getHeader("Authorization");
TokenValidator obj = new TokenValidator(token);//This class validates the Access token with WSO2
boolean tokenStatus = obj.gettokenStatus();
if(tokenStatus){
res.setHeader("Access-Control-Allow-Headers", "*");
res.setHeader("Access-Control-Max-Age", "3600");
chain.doFilter(req, res);
}else{
LOG.info("token validation is not scuesfull");
throw new SecurityException();
}
}

Related

Spring-security - httponlycookie into existing jwt intergration?

I have been told it is insecure to just use JWT without HttpOnly cookie when using a seperate frontend-service.
As suggested here:
http://cryto.net/~joepie91/blog/2016/06/19/stop-using-jwt-for-sessions-part-2-why-your-solution-doesnt-work/
HttpOnly Cookie: https://www.ictshore.com/ict-basics/httponly-cookie/
I currently have a working JWT system so i'm trying to upgrade this to support the cookie implementation.
I firstly changed my SecurityConfiguration to the following:
private final UserDetailsService uds;
private final PasswordEncoder bcpe;
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(uds).passwordEncoder(bcpe);
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.cors().and().csrf().disable();
http.addFilter(new CustomAuthenticationFilter(authenticationManagerBean()));
http.addFilterBefore(new CustomAuthorizationFilter(), UsernamePasswordAuthenticationFilter.class);
http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and().logout().deleteCookies(CustomAuthorizationFilter.COOKIE_NAME)
.and().authorizeRequests().antMatchers("/login/**", "/User/refreshToken", "/User/add").permitAll()
.and().authorizeRequests().antMatchers(GET, "/**").hasAnyAuthority("STUDENT")
.anyRequest().authenticated();
}
#Bean
#Override
public AuthenticationManager authenticationManagerBean() throws Exception{ // NO FUCKING IDEA WHAT THIS DOES
return super.authenticationManagerBean();
}
From here I am trying to insert the actual cookie implementation into my CustomAuthorizationFilter:
public class CustomAuthorizationFilter extends OncePerRequestFilter { // INTERCEPTS EVERY REQUEST
public static final String COOKIE_NAME = "auth_by_cookie";
#Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
if(request.getServletPath().equals("/login") || request.getServletPath().equals("/User/refreshToken/**")){ // DO NOTHING IF LOGGING IN OR REFRESHING TOKEN
filterChain.doFilter(request,response);
}
else{
String authorizationHeader = request.getHeader(AUTHORIZATION);
if(authorizationHeader != null && authorizationHeader.startsWith("Bearer ")){
try {
String token = authorizationHeader.substring("Bearer ".length());
//NEEDS SECURE AND ENCRYPTED vvvvvvv
Algorithm algorithm = Algorithm.HMAC256("secret".getBytes());
JWTVerifier verifier = JWT.require(algorithm).build(); // USING AUTH0
DecodedJWT decodedJWT = verifier.verify(token);
String email = decodedJWT.getSubject(); // GETS EMAIL
String[] roles = decodedJWT.getClaim("roles").asArray(String.class);
Collection<SimpleGrantedAuthority> authorities = new ArrayList<>();
stream(roles).forEach(role -> { authorities.add(new SimpleGrantedAuthority(role)); });
UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(email, null, authorities);
SecurityContextHolder.getContext().setAuthentication(authToken);
filterChain.doFilter(request, response);
}
catch (Exception e){
response.setHeader("error" , e.getMessage() );
response.setStatus(FORBIDDEN.value());
Map<String, String> error = new HashMap<>();
error.put("error_message", e.getMessage());
response.setContentType(APPLICATION_JSON_VALUE);
new ObjectMapper().writeValue(response.getOutputStream(), error);
}
}
else{ filterChain.doFilter(request, response); }
}
}
}
What I don't know is where to insert the cookie reading & where to wrap it. Does it wrap around the JWT?
I did see this implementation:
public class CookieAuthenticationFilter extends OncePerRequestFilter {
public static final String COOKIE_NAME = "auth_by_cookie";
#Override
protected void doFilterInternal(HttpServletRequest httpServletRequest,
HttpServletResponse httpServletResponse,
FilterChain filterChain) throws ServletException, IOException {
Optional<Cookie> cookieAuth = Stream.of(Optional.ofNullable(httpServletRequest.getCookies()).orElse(new Cookie[0]))
.filter(cookie -> COOKIE_NAME.equals(cookie.getName()))
.findFirst();
if (cookieAuth.isPresent()) {
SecurityContextHolder.getContext().setAuthentication(
new PreAuthenticatedAuthenticationToken(cookieAuth.get().getValue(), null));
}
filterChain.doFilter(httpServletRequest, httpServletResponse);
}
}
Though this mentions its the "authenticationFilter", I do have an authentication filter though it is less comparable to this CookieAuthenticationFilter than CustomAuthorizationFilter:
public class CustomAuthenticationFilter extends UsernamePasswordAuthenticationFilter {
private final AuthenticationManager authManager;
public CustomAuthenticationFilter authManagerFilter;
private UserService userService;
#Override // THIS OVERRIDES THE DEFAULT SPRING SECURITY IMPLEMENTATION
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
String email = request.getParameter("email");
String password = request.getParameter("password");
UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(email, password);
return authManager.authenticate(authToken);
}
#Override
protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authentication) throws IOException, ServletException {
// SPRING SECURITY BUILT IN USER
User springUserDetails = (User) authentication.getPrincipal();
// NEEDS SECURE AND ENCRYPTED vvvvvvv
Algorithm algorithm = Algorithm.HMAC256("secret".getBytes()); // THIS IS USING AUTH0 DEPENDENCY
String access_token = JWT.create()
.withSubject(springUserDetails.getUsername())
.withExpiresAt(new Date(System.currentTimeMillis() + 120 * 60 * 1000)) // this should be 2 hours
.withIssuer(request.getRequestURI().toString())
.withClaim("roles", springUserDetails.getAuthorities()
.stream()
.map(GrantedAuthority::getAuthority)
.collect(Collectors.toList()))
.sign(algorithm);
String refresh_token = JWT.create()
.withSubject(springUserDetails.getUsername())
.withExpiresAt(new Date(System.currentTimeMillis() + 120 * 60 * 1000)) // this should be 2 hours
.withIssuer(request.getRequestURI().toString())
.withClaim("roles", springUserDetails.getAuthorities()
.stream()
.map(GrantedAuthority::getAuthority)
.collect(Collectors.toList()))
.sign(algorithm);
Map<String, String> tokens = new HashMap<>();
tokens.put("access_token", access_token);
tokens.put("refresh_token", refresh_token);
response.setContentType(APPLICATION_JSON_VALUE);
new ObjectMapper().writeValue(response.getOutputStream(), tokens);
}
#Override
protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException failed) throws IOException, ServletException {
...
new ObjectMapper().writeValue(response.getOutputStream(), error);
}
}
}
Any suggestions are welcome!
By looking at all your custom code I would strongly recommend that you actually read the spring security documentation of the different authentication types that are available and look up the advantages and disadvantages.
And understand that there are security standards for how logins should be built and what you have built is insecure, non-scalable custom made which is very bad practice.
but here is a short recap:
FormLogin
The user authenticates themselves presenting a username and a password. In return, they will get a session cookie that contains a random string but is mapped to a key-value store on the server side.
The cookie is set to httpOnly and httpSecure which means it's harder to steal them and it's not vulnerable to XSS in the browser.
I just want to emphasize the cookie contains a random string, so if you want user information you either return the cookie after login and userinfo in the body or you do an additional call to a user endpoint and fetch user information.
The downside is that this solution does not scale if you want 5 backend servers you need something like Spring Session and set up a store, that stores the session so that it is shared between the backend servers.
Upside, we can just server-side invalidate the cookie whenever we want. We have full control.
oauth2
Well, this is the one most people know about, you want to login, and you are redirected, to an issuer (a different server). You authenticate with that server, the server gives you a temporary token that you can exchange for an opague token.
What is in opague token, well it's just a random text string that the issuer keeps track of.
Now when you want to call your backend you setup your backend as a resource server, that you present the token for in a header. The resource server extracts the token from the header, asks the issuer if the token is valid, and it answers yes or no.
Here you can revoke tokens, by going to the issuer and saying "this token is not valid anymore" and next time the token is presented it will check with the issuer that it is blocked and we are fine.
oauth2 + JWT
Like above but instead of having an opague token, we instead send a JWT to the client. So that, when the JWT has presented the resource server, does not have to ask the issuer if the token is valid. We can instead check the signature using a JWK. With this approach, we have one less call to the issuer to check the validity of the token.
JWT is just a format of a token. Opague token = random string, JWT = signed data in the format of JSON and used as a token.
JWTs were never meant to replace cookies, people just started using them instead of cookies.
But what we loose is the ability to know to revoke tokens. As we don't keep track of the JWTs in the issuer and we don't ask the issuer on each call.
We can reduce the risk here by having tokens that are short-lived. Maybe 5 minutes. But remember ITS STILL A RISK, for 5 mins malicious actors can do damage.
Your solution
If we look at your custom solution, which many people on the internet are building which has many many flaws is that you have built a FormLogin solution that gives out JWTs and hence comes with all the problems of JWTs.
So your token can be stolen in the browser as it does not have the security that comes with cookies. We have no ability to revoke tokens if it gets stolen. It is not scalable and it is custom written which means one bug and the entire application's data is compromised.
So basically all the bad things from the solutions above are combined here into one super bad solution.
My suggestion
You remove all your custom code and look at what type of application you have.
If it is a single server small application, use FormLogin, don't use JWTs at all. Cookies have worked for 20 years and they are still fine. Don't use JWTs just because want to use JWTs.
If you are writing a larger application, use a dedicated authorization server like okta, curity, spring authorization server, keycloak.
Then setup your servers to be resource servers using the built-in resource server functionality that comes with spring security and is documented in the JWT chapter in the docs.
JWTs were from the beginning never meant to be exposed to clients, since you can read everything in them they were meant to be used between servers to minimize calls to issuers because the data is signed so each server could check the signature by themselves.
Then the entire javascript community and lazy developers started writing custom insecure solutions to give out JWTs to the client.
Now everyone just googles a tutorial of spring security with JWT and builds something custom and insecure and then ask on stack overflow when "someone has pointed out that their solution is insecure".
If you are serious about building a secure login read the following:
Spring security official documentation, chapters formlogin, oauth2, JWT
The oauth2 specification
The JWT specification
Curity has good documentation about oauth2 https://curity.io/resources/learn/code-flow/
FormLogin spring
https://docs.spring.io/spring-security/reference/servlet/authentication/passwords/form.html
oauth2 spring
https://docs.spring.io/spring-security/reference/servlet/oauth2/index.html
configure your application to handle JWTs
https://docs.spring.io/spring-security/reference/servlet/oauth2/resource-server/jwt.html
Some pointers about your code
this is completely unneeded. You have overridden a function and then you are calling the default implementation, also think about your languages in your comments.
#Bean
#Override
public AuthenticationManager authenticationManagerBean() throws Exception{ // NO FUCKING IDEA WHAT THIS DOES
return super.authenticationManagerBean();
}
Also, this entire class can be removed
public class CustomAuthorizationFilter extends OncePerRequestFilter
If you want to handle JWTs and make your server a resource server all you do is as the documentation states https://docs.spring.io/spring-security/reference/servlet/oauth2/resource-server/jwt.html#oauth2resourceserver-jwt-sansboot
#Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(authorize -> authorize
.anyRequest().authenticated()
)
// This line sets up your server to use the built in filter
// and accept JWT tokens in headers
.oauth2ResourceServer(OAuth2ResourceServerConfigurer::jwt);
return http.build();
}
you can then setup a JWTDecoder using the built-in Nimbuslibrary that comes with spring security
#Bean
JwtDecoder jwtDecoder() {
return NimbusJwtDecoder.withJwkSetUri(this.jwkSetUri)
.jwsAlgorithm(RS512).jwsAlgorithm(ES512).build();
}
Since it's a Bean it will automatically get injected, so we don't have to manually set anything.
http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
Here you have stated that you want the server to be stateless which means you have disabled cookies as cookies are what the server uses to retain the state from the clients. And then you are trying to implement a custom cookie filter.
Once again, you have to decide, are you going to use FormLogin with cookies, or oauth2 + JWT because now you are doing a mish-mash between.
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(uds).passwordEncoder(bcpe);
}
Is most likely not needed as I assume that both uds and bcpe are beans, components, etc., and will automatically get injected. No need to make something a bean THEN manually set it. You make something a bean so you DON'T have to set it manually. But you are doing both.

Spring authentication scheme using the authentication header

I am using a spring boot application and I have a web security config adapter set up to authenticate each request using the jwt.
I want to expand my service to allow a different api end point to be authenticated using the header. One of the services I am integrating with sends a web hook and all it sends is the request with the custom header I set it up to include. How can I set up a specific endpoint to only authenticate using a custom header?
You could use a OncePerRequestFilter to filter the requests to that endpoint and return a 401 if they are do not contain your header with the right value.
You would define your filter:
public class HeaderSecurityFilter extends OncePerRequestFilter {
#Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
String value = request.getHeader("Token");
if(value == null || !value.equals("Secret")) {
response.sendError(401);
return;
}
chain.doFilter(request, response);
}
}
And then register it:
#Configuration
public class HeaderSecurityConfiguration {
#Bean
FilterRegistrationBean<HeaderSecurityFilter> filterRegistration() {
FilterRegistrationBean<HeaderSecurityFilter> registration = new FilterRegistrationBean<>();
registration.setFilter(new HeaderSecurityFilter());
registration.addUrlPatterns("/some/path/*");
return registration;
}
}
Which would require the header of Token be present with a value of Secret for anything under /some/path/*.
You would also need to ensure through your oauth configuration that you open up access to /some/path/*.

With Spring Security how do i determine if the current api request should be authenticated or not?

With spring security you can have public api endpoints that are accessible by everyone and endpoints that need to be authenticated before getting a response. In my app users authenticate via a jwt token. For logged in users right now the token is always checked, regardless of whether a public api endpoint gets the request or not.
I would like to know how to check if the current endpoint is a public endpoint or a authenticated one, that way i can alter the code so that the token checking is only done when the endpoint requires authentication.
I could add all public endpoints in a hashset and compare the current request endpoint with the public ones but that isn't efficient and also, some of the public endpoints contain wildcards (**) so that would make comparing a bit of a hassle.
This is the only information i could find:
Spring Security - check if web url is secure / protected
but its about JSP.
I can't get the request information from SecurityContextHolder.getContext() either. My guess is that i should get the information from org.springframework.security.config.annotation.web.builders.HttpSecurity because that is the same class used to define which endpoints don't require authentication. (with anthMatchers().permitall()). But i don't know which method to invoke and i'm not sure if HttpSecurity can even be autowired into another class. Can anyone give me some pointers?
Thank you
Assuming that you're using a separate filter for the token check, you can avoid the token check for public endpoints by overriding the protected boolean shouldNotFilter(HttpServletRequest request) method of the OncePerRequestFilter in your JwtTokenFilter. By default, this method will always return false. So all requests will get filtered. Overriding this method to return true for the public endpoints will give you the desired functionality.
And to check the requests with the wildcards(**), you can use AntPathRequestMatcher. So, you can do something like below.
public class JwtTokenFilter extends OncePerRequestFilter {
private static RequestMatcher requestMatcher;
public static void ignorePatterns(String... antPatterns) {
List<RequestMatcher> matchers = new ArrayList<>();
for (String pattern : antPatterns) {
matchers.add(new AntPathRequestMatcher(pattern, null));
}
requestMatcher = new OrRequestMatcher(matchers);
}
static {
final String[] publicEndPoints = {"/public-api/**","/resources/**"};
ignorePatterns(publicEndPoints);
}
#Override
protected boolean shouldNotFilter(HttpServletRequest request) throws ServletException {
return requestMatcher.matches(request);
}
#Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
throws ServletException, IOException {
....
}
}
Hope this helps!!

Spring-boot Zuul: Passing user ID between microservices

I have a Zuul Gateway proxy, where I check the authorization of token received from the user. Now, when this is request is passed on to other microservices to get the user-specific data, the user information needs to be passed from the gateway to the microservice.
Right now, I've added the user ID in the request header and I'm getting it at respective microservice's controller using API header annotation.
Is this the right way to pass the user information. Is there any other better way?
In case if anyone still facing this issue,
In Zuul Proxy add the header to RequestContext as below:
userId = jwtTokenUtil.getUsernameFromToken(jwtToken);
RequestContext ctx = RequestContext.getCurrentContext();
ctx.addZuulRequestHeader("userId", userId);
And then in the respective microservices write a custom filter and extract the value as below
#Component
public class MyFilter extends OncePerRequestFilter {
#Override
protected void doFilterInternal(HttpServletRequest request,
HttpServletResponse response,
FilterChain filterChain)
throws ServletException, IOException {
String userId = request.getHeaders("userId").nextElement();
logger.info("userId: "+userId);
filterChain.doFilter(request, response);
}
}

SSO with Spring security

I have an application, where user is pre-authorized by SSO and lands to my page, now I need to make a call to another rest api to get some data, which is running on another server, but it will be use the same authentication. So I just wanted to know, how I can provide the authentication process? Do I need to set the cookie what I am getting from the incoming request.
When the request lands on your page it should have a token or key, in the http AUTHORIZATION header, this should be used with a filter
public class AuthFilter extends OncePerRequestFilter {
private String failureUrl;
private SimpleUrlAuthenticationFailureHandler failureHandler = new SimpleUrlAuthenticationFailureHandler();
#Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
throws ServletException, IOException {
try {
// check your SSO token here
chain.doFilter(request, response);
} catch (OnlineDriverEnquiryException ode) {
failureHandler.setDefaultFailureUrl(failureUrl);
failureHandler.onAuthenticationFailure(request, response, new BadCredentialsException("Captcha invalid!"));
}
}
public String getFailureUrl() {
return failureUrl;
}
public void setFailureUrl(String failureUrl) {
this.failureUrl = failureUrl;
}
}
Also read this post on how to set up the auto config. Spring security without form login

Resources