• Spring Security使用心得


    某天,你的客户提出这样一个需求,在点击购买商品的时,如果用户没有注册,并且用户没有账号,这时用户去创建账户,然后要直接返回到想购买商品的付款页面。你会该如何基于Spring Security实现?

      Spring Security 是为基于Spring的应用程序提供声明式安全保护的安全性框架。它能够在Web请求级别和方法调用级别处理身份验证和授权。因为基于Spring框架,所以Spring Security充分利用依赖注入(dependency injection)和AOP.

      Spring Security提供了多种验证方式,最常见的有:XML配置和数据库验证方式。试想当我们点击购买商品并且没有登录的情况下,Spring Security 一般会跳到登录,但是登陆是由Spring帮我们实现的,所以我们跳到登陆页面后也就丢失了与商品的联系,其实这中间Spring会经历多个步骤,最后帮你验证你输入的结果。在跳进登陆页面前Spring会先调用默认 AuthenticationEntryPoint接口的方法,我们通过重载这个方法可以实现我们想进行的操作,这里就是保存用户点击的商品信息。

     1 public class SimpleEntryPointHandler implements AuthenticationEntryPoint {
     2 
     3     @Override
     4     public void commence(HttpServletRequest request, HttpServletResponse httpServletResponse, AuthenticationException e) throws  ServletException {
     5         if (request.getRequestURI().contains("/payment")) {
     6             httpServletResponse.sendRedirect("/");
     7         }
     8         else{
     9             request.getSession().setAttribute("reserveItemId", request.getParameter("itemId"));
    10             httpServletResponse.sendRedirect("/login");
    11         }
    12     }
    13 }

    spring-security部分配置: 

     1     <beans:bean id="simpleEntryPointHandler" class="com.trailblazers.freewheelers.security.SimpleEntryPointHandler"/>
     2 
     3     <http auto-config="true" entry-point-ref="simpleEntryPointHandler">
     4         <intercept-url pattern="/admin" access="ROLE_ADMIN"/>
     5         <intercept-url pattern="/item" access="ROLE_ADMIN"/>
     6         <intercept-url pattern="/reserve" access="ROLE_ADMIN, ROLE_USER"/>
     7         <intercept-url pattern="/deliveryAddress" access="ROLE_ADMIN, ROLE_USER"/>
     8         <intercept-url pattern="/userProfile" access="ROLE_ADMIN, ROLE_USER"/>
     9         <intercept-url pattern="/userProfile/**" access="ROLE_ADMIN"/>
    10         <intercept-url pattern="/payment" access="ROLE_ADMIN,ROLE_USER"/>
    11         <form-login login-page="/login" default-target-url="/userProfile"
    12                     authentication-failure-url="/loginfailed"/>
    13         <logout logout-success-url="/" />
    14         <access-denied-handler error-page="/403" />
    15       </http>

      解决了如何在login之前进行一些操作,接下来就是解决如何在创建用户之后进行登陆。Spring Security的验证是通过用户实现AuthenticationManager接口里的authenticate方法来验证的,常见的验证方法之前也提到了。所以当用户填好数据跳转到controller得时候我们手动实现这个方法,就能手动操作spring security来帮我们进行验证,具体如下:

     1 @Component
     2 public class AutoLogin {
     3 
     4     @Autowired
     5     @Qualifier("authenticationManager")
     6     protected AuthenticationManager authenticationManager;
     7 
     8     public void autoLogin(Account account, HttpServletRequest request) {
     9         UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
    10                 account.getEmailAddress(), account.getPassword());
    11 
    12         request.getSession();
    13 
    14         token.setDetails(new WebAuthenticationDetails(request));
    15         Authentication authenticatedUser = authenticationManager.authenticate(token);
    16 
    17         SecurityContextHolder.getContext(). setAuthentication(authenticatedUser);
    18     }
    19 }

    然后 Controller可以装配这个bean 调用authenticate就可达到登录效果。

    spring-security部分配置:

      此配置也就是数据库验证的测试provider,它制定了spring security验证手法,并且能够以bean的方式注入到java service里面,使其变得更加灵活。

     

    1     <authentication-manager alias="authenticationManager">
    2         <authentication-provider>
    3             <jdbc-user-service data-source-ref="myDataSource"
    4                                users-by-username-query="select email_address, password, enabled from account where upper(email_address)=upper(?)"
    5                                authorities-by-username-query="select a.email_address, ar.role from account a,
    6                                     account_role ar where a.account_name = ar.account_name and upper(a.email_address)=upper(?)"
    7                     />
    8         </authentication-provider>
    9     </authentication-manager>

      最后,本例子只是Spring Security中的一部分,Spring Security将系统安全逻辑从业务中分离出来,充分利用面向切面编程的思想,所以是一个值得深入研究的框架。通过这个切入点我们也可以探寻spring security执行的整个流程,更了解它的精髓。

    本例子代码:https://github.com/yeahyangliu/spring-security.git

  • 相关阅读:
    Selenium 3 + BrowserMobProxy 2.1.4 模拟浏览器访问 (含趟坑)
    macOS Sierra WiFi connecting problem
    Accumulator<Long> implements of JavaSparkContext in Spark1.x
    写了一个Android动画的启动界面
    用C#简单实现了数据的封装
    关于JAVA数据结构中的栈操作
    写了一个关于将XML文件导入数据库的程序(C#,sql server)
    经典电影里的数学应用
    初步学习多线程操作,代码不是完美的,欢迎大牛指点(运行通过)
    写了一份统计网站(ASP.NET)日访问量的源码(保存至数据库,部分性能待优化),运行通过。
  • 原文地址:https://www.cnblogs.com/Alex--Yang/p/3323181.html
Copyright © 2020-2023  润新知