Spring boot OAuth2 - JWT tokens in a cookie instead of GET request - java

I have a spring boot application that is using OAuth2 and it works good. The problem is that the access token and the refresh tokens is accessible with a GET request which making the tokens to be exposed and i want to switch it so the token will be stored in a cookie (httpOnly of-course) and will be accessible by the server side only.
I've searched the internet to find some example or explanation on how to do that but found nothing so far.
The only thing I've managed to do is to override the AuthenticationSuccessHandler the onAuthenticationSuccess() method and store the tokens in a cookie but it is only half work the question is how to override Spring's OAuth2 to use this cookie instead reading the token from the request headers?
And how to override the default access (GET request) so the tokens will be stored only in a cookie only?
Thanks in advance!

Related

Spring boot Client to invoke REST API secured by OAuth2

I am trying to write a client in spring which would invoke a REST api secured by OAuth2.
I have the following which i can use to get a token from Auth Server and then invoke a resource server.
Client ID, Client Secret, Username, Password and Access Token URL(URL to fetch the token from) , and Resource URL.
How do i write a client in spring boot which has above info so i could invoke the resource server URL to fetch my resource or do a POST.
After i get the access token which would have a Time To Live in ms(TTL), how do i cache it so i do not have to generate the token for every request. Is it good to cache the token ?
You can use declarative rest client - feign spring-cloud-starter-openfeign
for consuming the service and for cacheing the Spring cache to cache the access token.
Tip : call the access token and cache it and resume it in the subsequent calls.
Once the endpoint throws unauthroized exception or the token becomes invalid, then the retry mechanism in the feign client can make another call. To implement the retry, you need to have "spring-retry" as one of the dependency.
If you are using JWT tokens, the time-to-live is encoded in the token.
You can store it in local storage
You can store it as a cookie
You can store it in the browser session
You can implement an arbitrary way of storing your token
Where you supply your token is up to you.
It could be at any stage of communication (request parameter, header, on-demand).
I would suggest to do it like below using CloseableHttpClient
Put details like clientID, user creds, access token in the header of the Http call
Use CloseableHttpClient class -> execute method and pass the header along with URL.
Parse the response and extract the details
Store the retrieved token with either using Spring cache as mentioned by #Sivaraj or you can use a table to store the value along with a timestamp and fetch this value for next calls.

Spring Boot: What is the Right Way to Implement Basic Auth with httpheaders

I am consuming a secured Restful Service that grants access through Basic Auth (Username and Password). I have successfully accessed the API service and consumed its API; however, I am still confused as to what is the right way to implement HTTP headers with Basic Auth. I would assume I should authenticate only once, but the way I have constructed my code, it looks like I need to authenticate API with each service method I create.
Should I create a helper method with the authentication and call it on each service?
If you are using Basic Auth you need to always include credentials with your request. In case of OAuth, tokens have expiry. In this case, a token caching mechanism for the duration of a little bit less than the expiration duration would do the trick.
The Basic Auth is a kind of no status authentication. That means the server wouldn't record. Every time you need to provide username and password with your request. Each request is equal to the Server.
For another authentication called OAuth, the first time you request with username and password, the server will return a token to the frontend, which has an expiration period. So, you request every time with the token through the filter, where checks the expiry of the token. If it's not expired, using the same token for requests, otherwise, making a request to get another token.

httpSession.getAttribute("userId") returns null in spring Boot after some frequent API request from Angular front end

I am working on an app which have Frontend implemented in Angular 5 while the back end is in Spring Boot, I am using JWT tokens for authentication. Problem which i am unable to figure out is that When a user logs in I set userId in HttpSession on back end to use userId in later request by the same user.
session.setAttribute("userId", userData.getUsername());
If the same user make requests to back end's RestControllers with some interval like half a second, httpSession is returned correctly, if I make very quick requests httpSession starts returning NULL. I am making requests from Angular like this from various services.
getMyAccountList(){
return this.http.get('/api/account/getMyAccountList');
}
So i figured it out it was due Spring Security's Session Fixation behaviour, which is active by default. configuring HttpSecurity http in WebSecuirtyConfigurerAdapter can solve the problem. just need to add this configuration.
http.sessionManagement().sessionFixation().none();
also refer to this post : Apache Tomcat 7 Changing JSESSIONID on Every Request

Custom Authentication without username/password

I'm developing a web application (Back end : JAVA/ stateless REST API) (Front end : Angular) which eventually be placed inside another web application.(let's say parent app).
The parent app which is session based handles authentication by username/password and create token for each user. Once a user is able to login the parent application he or she should also able to access my application. It is good to mention the token can also be used to retrieve user data by a SOAP call from my application.
My idea is to get this token with my front end component and send it to my REST Api. I'm going to keep those tokens inside a concurrent hash map and for each call coming from FE I'll check the token on BE for authorization. I wonder if it is a correct approach?
When the parent app's session expires or the user logs out is the token invalidated?
If yes, how does your app know the token was invalidated? Is that the check the token on the BE? (which would need to be done for every request)
If a shared session is not an option then your approach is reasonable.
Also, for security the REST calls should always be HTTPS (refuse the request if not), and consider passing the token in a header instead of on the URL as a query parameter.

Spring: Generate new csrf token programmatically

I'm trying to make a webapp that will run on a single HTML page that will allow users to interact with the server through JavaScript and ajax. I'd like to make my requests safe against csrf attacks by including a csrf token in each request.
Because my webapp will only be operating on a single page, I can't use the ${_csrf.token} (or something like that) syntax in the view because the view is going to be a json object. Instead I'd like to have a url like "/security/csrf" that returns a token associated with the user's session. (Yes, this won't be a restful service exactly.)
Is there some way for me to generate a csrf token that Spring Security will be able to access when verifying a log-in? And additionally, is there a flaw in using csrf tokens in this way?
Token per request will kill caching. Token per session is just as safe.
In your first html response, include the csrf token in a meta tag, like the docs say: http://docs.spring.io/spring-security/site/docs/current/reference/html/csrf.html#csrf-include-csrf-token-ajax
You can use the same token across requests (in the same session)

Categories