use of org.springframework.security.web.authentication.WebAuthenticationDetails in project Asqatasun by Asqatasun.
the class LoginController method doGuestAutoLogin.
private void doGuestAutoLogin(HttpServletRequest request, String guestUser) {
try {
// Must be called from request filtered by Spring Security, otherwise SecurityContextHolder is not updated
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(guestUser, guestPassword);
token.setDetails(new WebAuthenticationDetails(request));
Authentication guest = authenticationManager.authenticate(token);
Logger.getLogger(this.getClass()).debug("Logging in with [{}]" + guest.getPrincipal());
SecurityContextHolder.getContext().setAuthentication(guest);
} catch (Exception e) {
SecurityContextHolder.getContext().setAuthentication(null);
Logger.getLogger(this.getClass()).debug("Failure in autoLogin", e);
}
}
use of org.springframework.security.web.authentication.WebAuthenticationDetails in project incubator-atlas by apache.
the class AtlasKnoxSSOAuthenticationFilter method doFilter.
/*
* doFilter of AtlasKnoxSSOAuthenticationFilter is the first in the filter list so in this it check for the request
* if the request is from browser and sso is enabled then it process the request against knox sso
* else if it's ssoenable and the request is with local login string then it show's the appropriate msg
* else if ssoenable is false then it contiunes with further filters as it was before sso
*/
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletResponse httpResponse = (HttpServletResponse) servletResponse;
AtlasResponseRequestWrapper responseWrapper = new AtlasResponseRequestWrapper(httpResponse);
responseWrapper.setHeader("X-Frame-Options", "DENY");
if (!ssoEnabled) {
filterChain.doFilter(servletRequest, servletResponse);
return;
}
HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;
if (LOG.isDebugEnabled()) {
LOG.debug("Knox doFilter {}", httpRequest.getRequestURI());
}
if (httpRequest.getSession() != null && httpRequest.getSession().getAttribute("locallogin") != null) {
servletRequest.setAttribute("ssoEnabled", false);
filterChain.doFilter(servletRequest, servletResponse);
return;
}
if (jwtProperties == null || isAuthenticated()) {
filterChain.doFilter(servletRequest, servletResponse);
return;
}
if (LOG.isDebugEnabled()) {
LOG.debug("Knox ssoEnabled {} {}", ssoEnabled, httpRequest.getRequestURI());
}
//if jwt properties are loaded and is current not authenticated then it will go for sso authentication
//Note : Need to remove !isAuthenticated() after knoxsso solve the bug from cross-origin script
HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
String serializedJWT = getJWTFromCookie(httpRequest);
// if we get the hadoop-jwt token from the cookies then will process it further
if (serializedJWT != null) {
SignedJWT jwtToken = null;
try {
jwtToken = SignedJWT.parse(serializedJWT);
boolean valid = validateToken(jwtToken);
//if the public key provide is correct and also token is not expired the process token
if (valid) {
String userName = jwtToken.getJWTClaimsSet().getSubject();
LOG.info("SSO login user : {} ", userName);
//if we get the userName from the token then log into atlas using the same user
if (userName != null && !userName.trim().isEmpty()) {
List<GrantedAuthority> grantedAuths = AtlasAuthenticationProvider.getAuthoritiesFromUGI(userName);
final UserDetails principal = new User(userName, "", grantedAuths);
final Authentication finalAuthentication = new UsernamePasswordAuthenticationToken(principal, "", grantedAuths);
WebAuthenticationDetails webDetails = new WebAuthenticationDetails(httpRequest);
((AbstractAuthenticationToken) finalAuthentication).setDetails(webDetails);
authenticationProvider.setSsoEnabled(ssoEnabled);
Authentication authentication = authenticationProvider.authenticate(finalAuthentication);
SecurityContextHolder.getContext().setAuthentication(authentication);
}
filterChain.doFilter(servletRequest, httpServletResponse);
} else {
// if the token is not valid then redirect to knox sso
redirectToKnox(httpRequest, httpServletResponse, filterChain);
}
} catch (ParseException e) {
LOG.warn("Unable to parse the JWT token", e);
redirectToKnox(httpRequest, httpServletResponse, filterChain);
}
} else {
redirectToKnox(httpRequest, httpServletResponse, filterChain);
}
}
use of org.springframework.security.web.authentication.WebAuthenticationDetails in project spring-security by spring-projects.
the class WebAuthenticationDetailsMixinTests method webAuthenticationDetailsSerializeTest.
@Test
public void webAuthenticationDetailsSerializeTest() throws JsonProcessingException, JSONException {
MockHttpServletRequest request = new MockHttpServletRequest();
request.setRemoteAddr("/localhost");
request.setSession(new MockHttpSession(null, "1"));
WebAuthenticationDetails details = new WebAuthenticationDetails(request);
String actualJson = mapper.writeValueAsString(details);
JSONAssert.assertEquals(AUTHENTICATION_DETAILS_JSON, actualJson, true);
}
use of org.springframework.security.web.authentication.WebAuthenticationDetails in project ORCID-Source by ORCID.
the class ShibbolethController method signinHandler.
@RequestMapping(value = { "/signin" }, method = RequestMethod.GET)
public ModelAndView signinHandler(HttpServletRequest request, HttpServletResponse response, @RequestHeader Map<String, String> headers, ModelAndView mav) {
LOGGER.info("Headers for shibboleth sign in: {}", headers);
checkEnabled();
mav.setViewName("social_link_signin");
String shibIdentityProvider = headers.get(InstitutionalSignInManager.SHIB_IDENTITY_PROVIDER_HEADER);
mav.addObject("providerId", shibIdentityProvider);
String displayName = institutionalSignInManager.retrieveDisplayName(headers);
mav.addObject("accountId", displayName);
RemoteUser remoteUser = institutionalSignInManager.retrieveRemoteUser(headers);
if (remoteUser == null) {
LOGGER.info("Failed federated log in for {}", shibIdentityProvider);
identityProviderManager.incrementFailedCount(shibIdentityProvider);
mav.addObject("unsupportedInstitution", true);
mav.addObject("institutionContactEmail", identityProviderManager.retrieveContactEmailByProviderid(shibIdentityProvider));
return mav;
}
// Check if the Shibboleth user is already linked to an ORCID account.
// If so sign them in automatically.
UserconnectionEntity userConnectionEntity = userConnectionManager.findByProviderIdAndProviderUserIdAndIdType(remoteUser.getUserId(), shibIdentityProvider, remoteUser.getIdType());
if (userConnectionEntity != null) {
LOGGER.info("Found existing user connection: {}", userConnectionEntity);
HeaderCheckResult checkHeadersResult = institutionalSignInManager.checkHeaders(parseOriginalHeaders(userConnectionEntity.getHeadersJson()), headers);
if (!checkHeadersResult.isSuccess()) {
mav.addObject("headerCheckFailed", true);
return mav;
}
try {
// Check if the user has been notified
if (!UserConnectionStatus.NOTIFIED.equals(userConnectionEntity.getConnectionSatus())) {
try {
institutionalSignInManager.sendNotification(userConnectionEntity.getOrcid(), shibIdentityProvider);
userConnectionEntity.setConnectionSatus(UserConnectionStatus.NOTIFIED);
} catch (UnsupportedEncodingException e) {
LOGGER.error("Unable to send institutional sign in notification to user " + userConnectionEntity.getOrcid(), e);
}
}
PreAuthenticatedAuthenticationToken token = new PreAuthenticatedAuthenticationToken(userConnectionEntity.getOrcid(), remoteUser.getUserId());
token.setDetails(new WebAuthenticationDetails(request));
Authentication authentication = authenticationManager.authenticate(token);
SecurityContextHolder.getContext().setAuthentication(authentication);
userConnectionEntity.setLastLogin(new Date());
userConnectionManager.update(userConnectionEntity);
} catch (AuthenticationException e) {
// this should never happen
SecurityContextHolder.getContext().setAuthentication(null);
LOGGER.warn("User {0} should have been logged-in via Shibboleth, but was unable to due to a problem", remoteUser, e);
}
return new ModelAndView("redirect:" + calculateRedirectUrl(request, response));
} else {
// To avoid confusion, force the user to login to ORCID again
mav.addObject("linkType", "shibboleth");
mav.addObject("firstName", (headers.get(InstitutionalSignInManager.GIVEN_NAME_HEADER) == null) ? "" : headers.get(InstitutionalSignInManager.GIVEN_NAME_HEADER));
mav.addObject("lastName", (headers.get(InstitutionalSignInManager.SN_HEADER) == null) ? "" : headers.get(InstitutionalSignInManager.SN_HEADER));
}
return mav;
}
use of org.springframework.security.web.authentication.WebAuthenticationDetails in project ORCID-Source by ORCID.
the class SocialController method signinHandler.
@RequestMapping(value = { "/access" }, method = RequestMethod.GET)
public ModelAndView signinHandler(HttpServletRequest request, HttpServletResponse response) {
SocialType connectionType = socialContext.isSignedIn(request, response);
if (connectionType != null) {
Map<String, String> userMap = retrieveUserDetails(connectionType);
String providerId = connectionType.value();
String userId = socialContext.getUserId();
UserconnectionEntity userConnectionEntity = userConnectionManager.findByProviderIdAndProviderUserId(userMap.get("providerUserId"), providerId);
if (userConnectionEntity != null) {
if (userConnectionEntity.isLinked()) {
UserconnectionPK pk = new UserconnectionPK(userId, providerId, userMap.get("providerUserId"));
userConnectionManager.updateLoginInformation(pk);
String aCredentials = new StringBuffer(providerId).append(":").append(userMap.get("providerUserId")).toString();
PreAuthenticatedAuthenticationToken token = new PreAuthenticatedAuthenticationToken(userConnectionEntity.getOrcid(), aCredentials);
token.setDetails(new WebAuthenticationDetails(request));
Authentication authentication = authenticationManager.authenticate(token);
SecurityContextHolder.getContext().setAuthentication(authentication);
return new ModelAndView("redirect:" + calculateRedirectUrl(request, response));
} else {
ModelAndView mav = new ModelAndView();
mav.setViewName("social_link_signin");
mav.addObject("providerId", providerId);
mav.addObject("accountId", getAccountIdForDisplay(userMap));
mav.addObject("linkType", "social");
mav.addObject("emailId", (userMap.get("email") == null) ? "" : userMap.get("email"));
mav.addObject("firstName", (userMap.get("firstName") == null) ? "" : userMap.get("firstName"));
mav.addObject("lastName", (userMap.get("lastName") == null) ? "" : userMap.get("lastName"));
return mav;
}
} else {
throw new UsernameNotFoundException("Could not find an orcid account associated with the email id.");
}
} else {
throw new UsernameNotFoundException("Could not find an orcid account associated with the email id.");
}
}
Aggregations