Include session in HTTP GET header - session-cookies

I try to create a header and use restTemplate (as the first code block) to send the request and want to pass the authorization (as the second code block), but I still get 401 Unauthorized. Could anybody give me a clue as to how to do it?
Thanks in advance.
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.add("Cookie", "userId=ADMIN");
ResponseEntity<String> response;
try {
response = restTemplate.exchange(restURL, HttpMethod.GET, new HttpEntity<Object>(headers), String.class);
...
}
public void filter(ServletRequest req, ServletResponse res, FilterChain chain) {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
if (request.getSession().getAttribute("userId") != null) {
...

Related

Spring security Oauth2 client modify authorization request going to Oauth server

I have use case where I need to add additional parameter(login hint)
to the authorize request. On researching I found that we can do this
by OAuth2AuthorizationRequestResolver. The problem I am facing is
that the HttpServeletRequest object present in this class is not the
instance of original HttpServletRequest initiated by client. So, I can
not fetch the query param or path param send by client and append them
to to the authorization URI as extra parameter(e.g. User name).
public class CustomAuthorizationRequestResolver implements OAuth2AuthorizationRequestResolver {
private OAuth2AuthorizationRequestResolver defaultResolver;
public CustomAuthorizationRequestResolver(ClientRegistrationRepository repo, String authorizationRequestBaseUri) {
defaultResolver = new DefaultOAuth2AuthorizationRequestResolver(repo, authorizationRequestBaseUri);
}
#Override
public OAuth2AuthorizationRequest resolve(HttpServletRequest request) {
defaultResolver.resolve(request);
OAuth2AuthorizationRequest req = defaultResolver.resolve(request);
if (req != null) {
req = customizeAuthorizationRequest(req, request);
}
return req;
}
#Override
public OAuth2AuthorizationRequest resolve(HttpServletRequest request, String clientRegistrationId) {
OAuth2AuthorizationRequest req = defaultResolver.resolve(request, clientRegistrationId);
if (req != null) {
req = customizeAuthorizationRequest(req, request);
}
return req;
}
private OAuth2AuthorizationRequest customizeAuthorizationRequest(OAuth2AuthorizationRequest req,
HttpServletRequest request) {
Map<String, Object> extraParams = new HashMap<String, Object>();
extraParams.putAll(req.getAdditionalParameters());
String userName = request.getParameter("userName");
extraParams.put("login_hint", userName);
return OAuth2AuthorizationRequest.from(req).additionalParameters(extraParams).build();
}
}
Any help would be appreciated.

Spring Security with oAuth2 CORS issue on spring boot

I am new to spring boot. I have implemented Spring Security with oAuth2 and get acesstoken successfully from spring Security. But when I try to request with token with "Authorization" header..
config.headers["Authorization"] = 'Bearer 0d634d2b-3900-4ca4-a462-cf729e8d0c72';
and my CORS filter is as :
#Component
#Order(Ordered.HIGHEST_PRECEDENCE)
public class RequestFilter implements Filter {
#Override
public void init(FilterConfig filterConfig) throws ServletException {
}
#Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
HttpServletRequest request = (HttpServletRequest) req;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT,DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
if (request.getMethod()!="OPTIONS") {
chain.doFilter(req, res);
} else {
}
}
#Override
public void destroy() {
}
}
But still it given CORS issue.
Please help me where I am wrong.
Problem solve. I have send token as wrong way
config.headers["Authorization"] = 'Bearer 0d634d2b-3900-4ca4-a462-cf729e8d0c72';
right way is:
config.headers.authorization = 'Bearer 0d634d2b-3900-4ca4-a462-cf729e8d0c72';
Try to set your Access-Control-Allow-Headers like this:
response.setHeader("Access-Control-Allow-Headers", "X-Requested-With, Authorization, Content-Type");

Session expiration management with Spring Session for a single page app

I use Spring Session and I am having issues with session management especially dealing with session expiration.
The idea is to return a custom Http Header to the client e.g. X-Application-Session-Is-New if the session has expired.
Here is what I came up with:
public class SessionDestroyedFilter extends OncePerRequestFilter {
//TODO: not always invoked!!
#Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
if (isAjaxRequest(request) && (isRequestedSessionInvalid(request) || isSessionNew(request))) {
response.addHeader("X-Application-Session-Is-New", "true");
}
filterChain.doFilter(request, response);
}
private boolean isRequestedSessionInvalid(HttpServletRequest request) {
return !request.isRequestedSessionIdValid();
}
private boolean isSessionNew(HttpServletRequest request) {
return request.getSession(false).isNew();
}
private boolean isAjaxRequest(HttpServletRequest request) {
return "XMLHttpRequest".equals(request.getHeader("X-Requested-With"));
}
}
The issue is that my filter does not seem to be always invoked upon session expiration perhaps because the request is not an ajax request and a new session ID is immediately created after that.
Can anyone please point me to an appropriate strategy to deal with session expiration on single page apps?
EDIT Following is currently not possible (instead do decoration)
Here are some related github issues (comment on them to fix them faster)
https://github.com/spring-projects/spring-session/issues/243
https://github.com/spring-projects/spring-session/issues/112
To accomplish this you have to use your own HttpSessionStrategy.
Here is an example if you are using CookieHttpSessionStrategy (the default one)
public class CustomHttpSessionStrategy extends CookieHttpSessionStrategy {
#Override
public void onInvalidateSession(HttpServletRequest request, HttpServletResponse response) {
super.onInvalidateSession(request, response);
response.addHeader("X-Application-Session-Is-New", "true");
}
}
If you want to add your header on new sessions also consider overriding onNewSession(Session, HttpServletRequest, HttpServletResponse).
This is Wrong
Please see my other answer
You should move your logic for adding X-Application-Session-Is-New after request is processed.
Try something like
#Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
filterChain.doFilter(request, response);
if (isAjaxRequest(request) && (isRequestedSessionInvalid(request) || isSessionNew(request))) {
response.addHeader("X-Application-Session-Is-New", "true");
}
}

Grails/SpringSecurity: Getting locale in LogoutHandler

In a grails app, I'm successfully getting the language the user has selected(added to url, "...?lang=xx_XX") like this:
def locale = RequestContextUtils.getLocale(request)
Using springsecurity, and got a special logout handler set up that works fine
grails.plugins.springsecurity.logout.handlerNames = ['securityContextLogoutHandler', 'myLogoutHandler']
I need to get the user selected locale in myLogoutHandler, but the following is not working (it only shows the browser default locale, not the one selected by the user)
class MyLogoutHandler implements LogoutHandler {
void logout(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) {
def locale2 = RequestContextUtils.getLocale(httpServletRequest);
}
}
I have also tried getting the session locale with:
RequestContextHolder.currentRequestAttributes().getProperties()
but that gives the same result, anyone got an idea how to get the locale from the MyLogoutHandler?
Workaround
The session appears to be cleared by spring-security but you can still send in parameters.
so in the controller for the logout page I got:
def index = {
def myParam = "bar"
redirect(uri: SpringSecurityUtils.securityConfig.logout.filterProcessesUrl + "?foo=" + myParam) // '/j_spring_security_logout'
}
And I just get the parameter in the LogoutHandler:
void logout(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) {
def myParam = httpServletRequest.parameterMap.get("foo")[0]
....
}
I can get the locales by using the code below:
class CustomLogoutSuccessHandler extends SimpleUrlLogoutSuccessHandler {
private static final ThreadLocal<Authentication> AUTH_HOLDER = new ThreadLocal<Authentication>()
void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
AUTH_HOLDER.set authentication
// reading locales...
request.locales.each {locale ->println locale.toString()}
try {
super.handle(request, response, authentication)
}
finally {
AUTH_HOLDER.remove()
}
}
#Override
protected String determineTargetUrl(HttpServletRequest request, HttpServletResponse response) {
Authentication auth = AUTH_HOLDER.get()
String url = super.determineTargetUrl(request, response)
// do something with the url based on session data..
url
}
}

JSF page redirect

We have a JSF2.0 application deployed in weblogic-10.3.4 , we have a requirement to give a user generic url ,say (http://web/apply?7777 ) . When user access this page ,based on query string value , user will be re-directed to client specific page,which can be one of 10 different pages.
So one approach is to have a apply.jsf page ,which has got a pre-render event ,which will re-direct the user to different page based on query string,
Is there any other better approach? not to have apply.xhtml.
Note: In web.xml ,we defined pageNotFound.xhtml in case if the page is not found.
You could use a simple servlet filter for this.
#WebFilter("/apply")
public class ApplyFilter implements Filter {
#Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
String queryString = request.getQueryString();
String redirectURL = determineItBasedOnQueryString(queryString);
if (redirectURL != null) {
response.sendRedirect(redirectURL);
} else {
response.sendError(HttpServletResponse.SC_NOT_FOUND);
}
}
// ...
}

Resources