【问题标题】:How to generate and manage token after spring security authenticationspring安全认证后如何生成和管理token
【发布时间】:2016-05-25 23:00:14
【问题描述】:

我有一个android应用程序,我在服务器端使用spring security进行身份验证和授权。首先,用户输入用户名和密码,并使用Rest Template通过请求将其发送到服务器控制器进行身份验证。我有完成了此用户名密码请求的身份验证部分。现在我必须为连续请求身份验证生成一个令牌。但我不知道该怎么做。这就是我的想法-

a) 生成并存储 AES 密钥。

b) 使用此 AES 密钥加密用户名 + 时间戳(您必须在此步骤后进行 base64 编码以避免任何特殊字符)。这将是您的用户令牌。

c) 使用 HMAC 密钥签署此令牌(再次将其存储在密钥库中)。

d) 将令牌与签名一起发送(使用 ; 作为分隔符)。

e) 将您在步骤 c 中获得的令牌与数据库中的用户名存储起来。

令牌将作为响应的一部分发送给客户端。 我不知道如何实现上述方法。我在网上搜索过,但没有找到任何有用的东西。 以下是我用于身份验证的代码。

try{
        System.out.println("Request received... ");
        Gson gson = new Gson();
        TestUser userChk=new TestUser();
        userChk=gson.fromJson(coaObj, TestUser.class);
        Authentication authenticationToken = new UsernamePasswordAuthenticationToken(userChk.getUserName(), userChk.getPassword());
        Authentication authentication = authenticationManager.authenticate(authenticationToken);
        SecurityContextHolder.getContext().setAuthentication(authentication);
        System.out.println("getAuthorities is "+authentication.getAuthorities()+" getCredentials "+authentication.getCredentials()+" getDetails "+authentication.getDetails()+" getPrincipal "+authentication.getPrincipal());
        return "Authenticated";
    }catch(Exception er){
        System.out.println("Authentication error "+er);
        return "Authentication failure";
    }

请有人帮我用这种方法生成令牌并管理它。

【问题讨论】:

    标签: authentication spring-security token resttemplate


    【解决方案1】:

    最近我参与了一个项目,其中我们为 Web 和移动应用程序公开了 REST API。您可以在身份验证成功后发送 cookie(以保持会话)。它也适用于移动应用程序。您需要扩展 SimpleUrlAuthenticationSuccessHandler 并发送 cookie 作为响应,如果您希望会话持续更长时间,您还可以设置 cookie 年龄。

    package com.arjun.security;
    
    import java.io.IOException;
    
    import javax.servlet.ServletException;
    import javax.servlet.http.Cookie;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.security.core.Authentication;
    import org.springframework.security.web.RedirectStrategy;
    import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
    import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
    import org.springframework.security.web.savedrequest.RequestCache;
    
    import com.google.gson.Gson;
    import com.google.gson.GsonBuilder;
    import com.informage.arnav.dto.response.LoginUserResponseDto;
    import com.informage.arnav.service.UserService;
    import com.informage.arnav.util.ApplicationUtil;
    
    public class AppSimpleUrlAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {
    
         @Autowired
        ApplicationUtil applicationUtil;
    
        @Autowired
        UserService userService;
    
        private RequestCache requestCache = new HttpSessionRequestCache();
    
        public AppSimpleUrlAuthenticationSuccessHandler() {
            super();
            setRedirectStrategy(new NoRedirectStrategy());
        }
    
        @Override
        public void onAuthenticationSuccess(HttpServletRequest request,
                                            HttpServletResponse response,
                                            Authentication authentication) throws ServletException,
            IOException {
    
            super.onAuthenticationSuccess(request, response, authentication);
    
            AppUserDetails appUserDetails = applicationUtil.getCurrentUser();
            appUserDetails.setSessionId(request.getSession().getId());
            Cookie[] cookies = request.getCookies();
            if (cookies.length > 0) {
                for (Cookie cookie : cookies) {
                    if (cookie != null) {
                        if (cookie.getName().equals("JSESSIONID")) {
                            String value = cookie.getValue();
                            cookie.setMaxAge(1555200000);
                            cookie.setPath("/");
                            //cookie.setHttpOnly(true);
                            response.addCookie(cookie);
                        }
                    }
                }
            }
    
            LoginUserResponseDto dto = userService.getDtoFromUserName(appUserDetails.getUsername());
            Gson gson = new GsonBuilder().create();
            String json = gson.toJson(dto);
            response.getWriter().write(json);
            response.addHeader("Content-Type", "application/json");
            response.getWriter().flush();
    
        }
    
    }
    

    getCurrentUser 方法的代码是:

    public AppUserDetails getCurrentUser() {
        final Object principal = SecurityContextHolder.getContext()
                                                      .getAuthentication()
                                                      .getPrincipal();
        final AppUserDetails appUserDetails;
        if (principal != null && principal instanceof AppUserDetails) {
            appUserDetails = (AppUserDetails) principal;
        } else {
            appUserDetails = null;
        }
    
        return appUserDetails;
    }
    

    最后你需要在你的 security.xml 文件中配置它。

    <beans:property name="authenticationSuccessHandler"
            ref="mySuccessHandler" />
    
    <beans:bean id="mySuccessHandler"
        class="com.informage.arnav.security.AppSimpleUrlAuthenticationSuccessHandler" />
    

    【讨论】:

    • 我认为 cookie 不是一种安全的方法。
    猜你喜欢
    • 2013-12-11
    • 2022-11-28
    • 2014-10-30
    • 1970-01-01
    • 2017-10-25
    • 2021-01-17
    • 1970-01-01
    • 2016-08-15
    • 2015-03-21
    相关资源
    最近更新 更多