org.springframework.security.web.savedrequest.DefaultSavedRequest Java Examples

The following examples show how to use org.springframework.security.web.savedrequest.DefaultSavedRequest. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: LoginProcessSetTenantFilter.java    From microservices-platform with Apache License 2.0 6 votes vote down vote up
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
    try {
        DefaultSavedRequest savedRequest = (DefaultSavedRequest)request.getSession().getAttribute(SAVED_REQUEST);
        if (savedRequest != null) {
            String[] clientIds = savedRequest.getParameterValues("client_id");
            if (ArrayUtil.isNotEmpty(clientIds)) {
                //保存租户id
                TenantContextHolder.setTenant(clientIds[0]);
            }
        }
        chain.doFilter(request, response);
    } finally {
        TenantContextHolder.clear();
    }
}
 
Example #2
Source File: LoginController.java    From cloud-native-microservice-strangler-example with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Generate an authorization parameter map from the session's token request
 * @param defaultSavedRequest the default saved request from the session
 * @return a map of parameters containing the OAuth2 request details
 */
private Map<String, String> getAuthParameters(DefaultSavedRequest defaultSavedRequest) {
    Map<String, String> authParams = new HashMap<>();

    authParams.put(OAuth2Utils.CLIENT_ID,
            defaultSavedRequest.getParameterMap().get(OAuth2Utils.CLIENT_ID)[0]);

    authParams.put(OAuth2Utils.REDIRECT_URI,
            defaultSavedRequest.getParameterMap().get(OAuth2Utils.REDIRECT_URI)[0]);

    if(defaultSavedRequest.getParameterMap().get(OAuth2Utils.STATE) != null) {
        authParams.put(OAuth2Utils.STATE,
                defaultSavedRequest.getParameterMap().get(OAuth2Utils.STATE)[0]);
    }

    authParams.put(OAuth2Utils.RESPONSE_TYPE, "code");
    authParams.put(OAuth2Utils.USER_OAUTH_APPROVAL, "true");
    authParams.put(OAuth2Utils.GRANT_TYPE, "authorization_code");
    return authParams;
}
 
Example #3
Source File: LoginController.java    From spring-cloud-event-sourcing-example with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Generate an authorization parameter map from the session's token request
 * @param defaultSavedRequest the default saved request from the session
 * @return a map of parameters containing the OAuth2 request details
 */
private Map<String, String> getAuthParameters(DefaultSavedRequest defaultSavedRequest) {
    Map<String, String> authParams = new HashMap<>();

    authParams.put(OAuth2Utils.CLIENT_ID,
            defaultSavedRequest.getParameterMap().get(OAuth2Utils.CLIENT_ID)[0]);

    authParams.put(OAuth2Utils.REDIRECT_URI,
            defaultSavedRequest.getParameterMap().get(OAuth2Utils.REDIRECT_URI)[0]);

    if(defaultSavedRequest.getParameterMap().get(OAuth2Utils.STATE) != null) {
        authParams.put(OAuth2Utils.STATE,
                defaultSavedRequest.getParameterMap().get(OAuth2Utils.STATE)[0]);
    }

    authParams.put(OAuth2Utils.RESPONSE_TYPE, "code");
    authParams.put(OAuth2Utils.USER_OAUTH_APPROVAL, "true");
    authParams.put(OAuth2Utils.GRANT_TYPE, "authorization_code");
    return authParams;
}
 
Example #4
Source File: LoginController.java    From microservices-event-sourcing with Apache License 2.0 5 votes vote down vote up
@RequestMapping(value = "/login", method = RequestMethod.POST)
public String login(HttpServletRequest request, HttpServletResponse response, Model model) {
    HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, response);
    httpSessionSecurityContextRepository.loadContext(holder);

    try {
        // 使用提供的证书认证用户
        List<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList("ROLE_USER", "ROLE_ADMIN");
        Authentication auth = new UsernamePasswordAuthenticationToken(request.getParameter("username"), request.getParameter("password"), authorities);
        SecurityContextHolder.getContext().setAuthentication(authenticationManager.authenticate(auth));

        // 认证用户
        if(!auth.isAuthenticated())
            throw new CredentialException("用户不能够被认证");
    } catch (Exception ex) {
        // 用户不能够被认证,重定向回登录页
        logger.info(ex);
        return "login";
    }

    // 从会话得到默认保存的请求
    DefaultSavedRequest defaultSavedRequest = (DefaultSavedRequest) request.getSession().getAttribute("SPRING_SECURITY_SAVED_REQUEST");
    // 为令牌请求生成认证参数Map
    Map<String, String> authParams = getAuthParameters(defaultSavedRequest);
    AuthorizationRequest authRequest = new DefaultOAuth2RequestFactory(clientDetailsService).createAuthorizationRequest(authParams);
    authRequest.setAuthorities(AuthorityUtils.createAuthorityList("ROLE_USER", "ROLE_ADMIN"));
    model.addAttribute("authorizationRequest", authRequest);

    httpSessionSecurityContextRepository.saveContext(SecurityContextHolder.getContext(), holder.getRequest(), holder.getResponse());
    return "authorize";
}
 
Example #5
Source File: LoginController.java    From microservices-event-sourcing with Apache License 2.0 5 votes vote down vote up
/**
 * 为会话的令牌请求生成认证参数Map
 * @param defaultSavedRequest 会话中默认保存的SPRING_SECURITY_SAVED_REQUEST请求
 * @return 包含OAuth2请求明细的参数Map
 */
private Map<String,String> getAuthParameters(DefaultSavedRequest defaultSavedRequest) {
    Map<String, String> authParams = new HashMap<>();
    authParams.put(OAuth2Utils.CLIENT_ID, defaultSavedRequest.getParameterMap().get(OAuth2Utils.CLIENT_ID)[0]);
    authParams.put(OAuth2Utils.REDIRECT_URI, defaultSavedRequest.getParameterMap().get(OAuth2Utils.REDIRECT_URI)[0]);
    if(defaultSavedRequest.getParameterMap().get(OAuth2Utils.STATE) != null) {
        authParams.put(OAuth2Utils.STATE, defaultSavedRequest.getParameterMap().get(OAuth2Utils.STATE)[0]);
    }

    authParams.put(OAuth2Utils.RESPONSE_TYPE, "code");
    authParams.put(OAuth2Utils.USER_OAUTH_APPROVAL, "true");
    authParams.put(OAuth2Utils.GRANT_TYPE, "authorization_code");

    return authParams;
}
 
Example #6
Source File: SimpleRequestCache.java    From para with Apache License 2.0 5 votes vote down vote up
/**
 * Saves a request in cache.
 * @param request HTTP request
 * @param response HTTP response
 */
@Override
public void saveRequest(HttpServletRequest request, HttpServletResponse response) {
	if (anyRequestMatcher.matches(request) && !ajaxRequestMatcher.matches(request)) {
		DefaultSavedRequest savedRequest = new DefaultSavedRequest(request, portResolver);
		HttpUtils.setStateParam(Config.RETURNTO_COOKIE,
				Utils.base64enc(savedRequest.getRedirectUrl().getBytes()), request, response);
	}
}
 
Example #7
Source File: LoginController.java    From cloud-native-microservice-strangler-example with GNU General Public License v3.0 4 votes vote down vote up
@RequestMapping(value = "/login", method = RequestMethod.POST)
public String login(HttpServletRequest request, HttpServletResponse response, Model model) {

    HttpRequestResponseHolder responseHolder = new HttpRequestResponseHolder(request, response);
    sessionRepository.loadContext(responseHolder);

    try {
        // Authenticate the user with the supplied credentials
        List<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList("ROLE_USER", "ROLE_ADMIN");

        Authentication auth =
                new UsernamePasswordAuthenticationToken(request.getParameter("username"),
                        request.getParameter("password"), authorities);

        SecurityContextHolder.getContext()
                .setAuthentication(authenticationManager.authenticate(auth));

        // Authenticate the user
        if(!authenticationManager.authenticate(auth).isAuthenticated())
            throw new CredentialException("User could not be authenticated");

    } catch (Exception ex) {
        // The user couldn't be authenticated, redirect back to login
        ex.printStackTrace();
        return "login";
    }

    // Get the default saved request from session
    DefaultSavedRequest defaultSavedRequest = ((DefaultSavedRequest) request.getSession().getAttribute("SPRING_SECURITY_SAVED_REQUEST"));

    // Generate an authorization parameter map for the token request
    Map<String, String> authParams = getAuthParameters(defaultSavedRequest);

    // Create the authorization request and put it in the view model
    AuthorizationRequest authRequest = new DefaultOAuth2RequestFactory(clients).createAuthorizationRequest(authParams);
    authRequest.setAuthorities(AuthorityUtils.createAuthorityList("ROLE_USER", "ROLE_ADMIN"));
    sessionRepository.saveContext(SecurityContextHolder.getContext(), responseHolder.getRequest(), responseHolder.getResponse());
    model.addAttribute("authorizationRequest", authRequest);

    // Return the token authorization view
    return "authorize";
}
 
Example #8
Source File: LoginController.java    From spring-cloud-event-sourcing-example with GNU General Public License v3.0 4 votes vote down vote up
@RequestMapping(value = "/login", method = RequestMethod.POST)
public String login(HttpServletRequest request, HttpServletResponse response, Model model) {

    HttpRequestResponseHolder responseHolder = new HttpRequestResponseHolder(request, response);
    sessionRepository.loadContext(responseHolder);

    try {
        // Authenticate the user with the supplied credentials
        List<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList("ROLE_USER", "ROLE_ADMIN");

        Authentication auth =
                new UsernamePasswordAuthenticationToken(request.getParameter("username"),
                        request.getParameter("password"), authorities);

        SecurityContextHolder.getContext()
                .setAuthentication(authenticationManager.authenticate(auth));

        // Authenticate the user
        if(!authenticationManager.authenticate(auth).isAuthenticated())
            throw new CredentialException("User could not be authenticated");

    } catch (Exception ex) {
        // The user couldn't be authenticated, redirect back to login
        ex.printStackTrace();
        return "login";
    }

    // Get the default saved request from session
    DefaultSavedRequest defaultSavedRequest = ((DefaultSavedRequest) request.getSession().getAttribute("SPRING_SECURITY_SAVED_REQUEST"));

    // Generate an authorization parameter map for the token request
    Map<String, String> authParams = getAuthParameters(defaultSavedRequest);

    // Create the authorization request and put it in the view model
    AuthorizationRequest authRequest = new DefaultOAuth2RequestFactory(clients).createAuthorizationRequest(authParams);
    authRequest.setAuthorities(AuthorityUtils.createAuthorityList("ROLE_USER", "ROLE_ADMIN"));
    sessionRepository.saveContext(SecurityContextHolder.getContext(), responseHolder.getRequest(), responseHolder.getResponse());
    model.addAttribute("authorizationRequest", authRequest);

    // Return the token authorization view
    return "authorize";
}
 
Example #9
Source File: PlayerFormLoginSuccessAuthenticationHandler.java    From codenjoy with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void onAuthenticationSuccess(HttpServletRequest request,
                                    HttpServletResponse response, Authentication authentication)
        throws ServletException, IOException {
    // reused logic from SavedRequestAwareAuthenticationSuccessHandler::onAuthenticationSuccess
    SavedRequest savedRequest = requestCache.getRequest(request, response);

    if (savedRequest == null) {
        super.onAuthenticationSuccess(request, response, authentication);

        return;
    }
    String targetUrlParameter = getTargetUrlParameter();
    if (isAlwaysUseDefaultTargetUrl()
            || (targetUrlParameter != null && StringUtils.hasText(request
            .getParameter(targetUrlParameter)))) {
        requestCache.removeRequest(request, response);
        super.onAuthenticationSuccess(request, response, authentication);

        return;
    }

    clearAuthenticationAttributes(request);
    // end of logic reuse

    if (savedRequest instanceof DefaultSavedRequest) {
        String requestURI = ((DefaultSavedRequest) savedRequest).getRequestURI();
        if (requestURI != null && requestURI.endsWith(AdminController.URI)) {
            getRedirectStrategy().sendRedirect(request, response, AdminController.URI);
            return;
        }
    }

    Registration.User principal = (Registration.User) authentication.getPrincipal();
    String gameName = obtainGameName(request, savedRequest);
    String roomName = gameName; // TODO ROOM тут надо получить roomName как-то
    // TODO #984 как воспроизвести чтобы понять зачем этот костыль нужен?
    // Мы логинимся как нормальный юзер. Потом вылогиниваемся и снова
    // залогиниваемся как админ и получаем тут ошибку. Почему? Потому
    // что у нас в requestCache какого-то фига сохоанено с прошлого раза
    // DefaultSavedRequest и мы пытаемся зайти как нормальный юзер
    // но на форме логина не было выбрано игрушки потому что там стоит
    // <c:if test="${not adminLogin}">. Как сделать так, чтобы после логаута
    // из сессии удалялся DefaultSavedRequest я не разобрался, в том и туду,
    // а пока тут повисит этот if. Надеюсь он нигде не стрельнет в делах обычных юзеров
    if (gameName == null) {
        getRedirectStrategy().sendRedirect(request, response, AdminController.URI);
        return;
    }
    String targetUrl = "/" + registrationService.register(principal.getId(), 
            principal.getCode(), roomName, gameName, request.getRemoteAddr());

    log.debug("Redirecting to  URL: " + targetUrl);

    getRedirectStrategy().sendRedirect(request, response, targetUrl);
}
 
Example #10
Source File: SessionUtils.java    From gocd with Apache License 2.0 4 votes vote down vote up
public static void saveRequest(HttpServletRequest request) {
    saveRequest(request, new DefaultSavedRequest(request, PORT_RESOLVER));
}