zoukankan      html  css  js  c++  java
  • Spring Security 4 使用@PreAuthorize,@PostAuthorize, @Secured, EL实现方法安全

    【相关已翻译的本系列其他文章,点击分类里面的spring security 4】

    上一篇:Spring Security 4 整合Hibernate 实现持久化登录验证(带源码)

    原文地址:http://websystique.com/spring-security/spring-security-4-method-security-using-preauthorize-postauthorize-secured-el/


    本文探讨Spring Security 4 基于@PreAuthorize, @PostAuthorize, @Secured和 Spring EL表达式的方法级的安全。

    想要开启Spring方法级安全,你需要在已经添加了@Configuration注解的类上再添加@EnableGlobalMethodSecurity注解:

    1. package com.websystique.springsecurity.configuration;  
    2.    
    3. import org.springframework.beans.factory.annotation.Autowired;  
    4. import org.springframework.context.annotation.Configuration;  
    5. import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;  
    6. import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;  
    7. import org.springframework.security.config.annotation.web.builders.HttpSecurity;  
    8. import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;  
    9. import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;  
    10.    
    11. @Configuration  
    12. @EnableWebSecurity  
    13. @EnableGlobalMethodSecurity(prePostEnabled = true)  
    14. public class SecurityConfiguration extends WebSecurityConfigurerAdapter {  
    15.    
    16.        
    17.     @Autowired  
    18.     public void configureGlobalSecurity(AuthenticationManagerBuilder auth) throws Exception {  
    19.         auth.inMemoryAuthentication().withUser("bill").password("abc123").roles("USER");  
    20.         auth.inMemoryAuthentication().withUser("admin").password("root123").roles("ADMIN");  
    21.         auth.inMemoryAuthentication().withUser("dba").password("root123").roles("ADMIN","DBA");  
    22.     }  
    23.        
    24.     @Override  
    25.     protected void configure(HttpSecurity http) throws Exception {  
    26.          
    27.       http.authorizeRequests()  
    28.         .antMatchers("/""/home").access("hasRole('USER') or hasRole('ADMIN') or hasRole('DBA')")  
    29.         .and().formLogin().loginPage("/login")  
    30.         .usernameParameter("ssoId").passwordParameter("password")  
    31.         .and().exceptionHandling().accessDeniedPage("/Access_Denied");  
    32.     }  
    33. }  
    @EnableGlobalMethodSecurity 开启Spring
    Security 全局方法安全,等价的XML配置如下:

    1. <beans:beans xmlns="http://www.springframework.org/schema/security"  
    2.     xmlns:beans="http://www.springframework.org/schema/beans"  
    3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
    4.     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd  
    5.     http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-4.0.xsd">  
    6.         
    7.     <http auto-config="true" >  
    8.         <intercept-url pattern="/"     access="hasRole('USER') or hasRole('ADMIN') and hasRole('DBA')" />  
    9.         <intercept-url pattern="/home" access="hasRole('USER') or hasRole('ADMIN') and hasRole('DBA')" />  
    10.         <form-login  login-page="/login"  
    11.                      username-parameter="ssoId"  
    12.                      password-parameter="password"  
    13.                      authentication-failure-url="/Access_Denied" />  
    14.     </http>  
    15.        
    16.     <global-method-security pre-post-annotations="enabled"/>  
    17.    
    18.     <authentication-manager >  
    19.         <authentication-provider>  
    20.             <user-service>  
    21.                 <user name="bill"  password="abc123"  authorities="ROLE_USER" />  
    22.                 <user name="admin" password="root123" authorities="ROLE_ADMIN" />  
    23.                 <user name="dba"   password="root123" authorities="ROLE_ADMIN,ROLE_DBA" />  
    24.             </user-service>  
    25.         </authentication-provider>  
    26.     </authentication-manager>  
    27.        
    28. </beans:beans>  

    注意: @EnableGlobalMethodSecurity 可以配置多个参数:

    • prePostEnabled :决定Spring Security的前注解是否可用 [@PreAuthorize,@PostAuthorize,..] 
    • secureEnabled : 决定是否Spring Security的保障注解 [@Secured] 是否可用
    • jsr250Enabled :决定 JSR-250 annotations 注解[@RolesAllowed..] 是否可用.

    You can enable more than one type of annotation in the same application, but only one type should be used for any interface or class as the behavior will not be well-defined otherwise. If two annotations are found which apply to a particular method, then only one of them will be applied.

    在同一个应用程序中,可以启用多个类型的注解,但是只应该设置一个注解对于行为类的接口或者类。如果将2个注解同事应用于某一特定方法,则只有其中一个将被应用。

    我们将研究上面提到的前两个注解。

    @Secured

    此注释是用来定义业务方法的安全配置属性的列表。您可以在需要安全[角色/权限等]的方法上指定 @Secured,并且只有那些角色/权限的用户才可以调用该方法。如果有人不具备要求的角色/权限但试图调用此方法,将会抛出AccessDenied 异常。

    @Secured 源于 Spring之前版本.它有一个局限就是不支持Spring EL表达式。可以看看下面的例子:

    1. package com.websystique.springsecurity.service;  
    2.    
    3. import org.springframework.security.access.annotation.Secured;  
    4.    
    5.    
    6. public interface UserService {  
    7.    
    8.     List<User> findAllUsers();  
    9.    
    10.     @Secured("ROLE_ADMIN")  
    11.     void updateUser(User user);  
    12.    
    13.     @Secured({ "ROLE_DBA""ROLE_ADMIN" })  
    14.     void deleteUser();  
    15.        
    16. }  

    在上面的例子中,updateUser 方法只能被拥有ADMIN 权限的用户调用。deleteUser 方法只能够被拥有DBA 或者ADMIN 权限的用户调用。

    如果有不具有声明的权限的用户调用此方法,将抛出AccessDenied异常。

    如果你想指定AND(和)这个条件,我的意思说deleteUser 方法只能被同时拥有ADMIN & DBA 。但是仅仅通过使用 @Secured注解是无法实现的。

    但是你可以使用Spring的新的注解@PreAuthorize/@PostAuthorize(支持Spring EL),使得实现上面的功能成为可能,而且无限制。

    @PreAuthorize / @PostAuthorize

    Spring的 @PreAuthorize/@PostAuthorize 注解更适合方法级的安全,也支持Spring 表达式语言,提供了基于表达式的访问控制。

    @PreAuthorize 注解适合进入方法前的权限验证, @PreAuthorize可以将登录用户的roles/permissions参数传到方法中。

    @PostAuthorize 注解使用并不多,在方法执行后再进行权限验证。 

    所以它适合验证带有返回值的权限。Spring EL 提供 返回对象能够在表达式语言中获取返回的对象returnObject

    请参考 Common Built-In Expressions 获取支持的表达式.

    现在言归正常,使用@PreAuthorize / @PostAuthorize注解

    1. package com.websystique.springsecurity.service;  
    2.    
    3. import org.springframework.security.access.prepost.PostAuthorize;  
    4. import org.springframework.security.access.prepost.PreAuthorize;  
    5.    
    6. import com.websystique.springsecurity.model.User;  
    7.    
    8.    
    9. public interface UserService {  
    10.    
    11.     List<User> findAllUsers();  
    12.    
    13.     @PostAuthorize ("returnObject.type == authentication.name")  
    14.     User findById(int id);  
    15.    
    16.     @PreAuthorize("hasRole('ADMIN')")  
    17.     void updateUser(User user);  
    18.        
    19.     @PreAuthorize("hasRole('ADMIN') AND hasRole('DBA')")  
    20.     void deleteUser(int id);  
    21.    
    22. }  


    由于 @PreAuthorize可以使用Spring 表达式语言, 使用EL表达式可以轻易的表示任意条件. deleteUser方法 可以被拥有ADMIN & DBA角色的用户调用 .

    另外,我们增加了带有@PostAuthorize注解的findById()方法。通过@PostAuthorize注解 method(User object)的返回值在Spring表达式语言中可以通过returnObject 来使用。在例子中我们确保登录用户只能获取他自己的用户对象。

    上面就是@Secured, @PreAuthorize, @PostAuthorize 和EL的使用

    下面提到的service实现, User 模型& 控制器

    1. package com.websystique.springsecurity.service;  
    2.    
    3.    
    4. import java.util.ArrayList;  
    5. import java.util.List;  
    6.    
    7. import org.springframework.stereotype.Service;  
    8. import org.springframework.transaction.annotation.Transactional;  
    9.    
    10. import com.websystique.springsecurity.model.User;  
    11.    
    12. @Service("userService")  
    13. @Transactional  
    14. public class UserServiceImpl implements UserService{  
    15.    
    16.     static List<User> users = new ArrayList<User>();  
    17.        
    18.     static{  
    19.         users = populateUser();  
    20.     }  
    21.        
    22.     public List<User> findAllUsers(){  
    23.         return users;  
    24.     }  
    25.        
    26.     public User findById(int id){  
    27.         for(User u : users){  
    28.             if(u.getId()==id){  
    29.                 return u;  
    30.             }  
    31.         }  
    32.         return null;  
    33.     }  
    34.        
    35.     public void updateUser(User user) {  
    36.         System.out.println("Only an Admin can Update a User");  
    37.         User u = findById(user.getId());  
    38.         users.remove(u);  
    39.         u.setFirstName(user.getFirstName());  
    40.         u.setLastName(user.getLastName());  
    41.         u.setType(user.getType());  
    42.         users.add(u);  
    43.     }  
    44.        
    45.     public void deleteUser(int id){  
    46.         User u = findById(id);  
    47.         users.remove(u);  
    48.     }  
    49.        
    50.     private static List<User> populateUser(){  
    51.         List<User> users = new ArrayList<User>();  
    52.         users.add(new User(1,"Sam","Disilva","admin"));  
    53.         users.add(new User(2,"Kevin","Brayn","admin"));  
    54.         users.add(new User(3,"Nina","Conor","dba"));  
    55.         users.add(new User(4,"Tito","Menz","dba"));  
    56.         return users;  
    57.     }  
    58.    
    59. }  

    1. public class User {  
    2.    
    3.     private int id;  
    4.        
    5.     private String firstName;  
    6.        
    7.     private String lastName;  
    8.        
    9.     private String type;  
    10.    
    11. //getters/setters  
    12. }  

    1. package com.websystique.springsecurity.controller;  
    2.    
    3. import java.util.List;  
    4.    
    5. import javax.servlet.http.HttpServletRequest;  
    6. import javax.servlet.http.HttpServletResponse;  
    7.    
    8. import org.springframework.beans.factory.annotation.Autowired;  
    9. import org.springframework.security.core.Authentication;  
    10. import org.springframework.security.core.context.SecurityContextHolder;  
    11. import org.springframework.security.core.userdetails.UserDetails;  
    12. import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;  
    13. import org.springframework.stereotype.Controller;  
    14. import org.springframework.ui.ModelMap;  
    15. import org.springframework.web.bind.annotation.PathVariable;  
    16. import org.springframework.web.bind.annotation.RequestMapping;  
    17. import org.springframework.web.bind.annotation.RequestMethod;  
    18.    
    19. import com.websystique.springsecurity.model.User;  
    20. import com.websystique.springsecurity.service.UserService;  
    21.    
    22. @Controller  
    23. public class HelloWorldController {  
    24.    
    25.     @Autowired  
    26.     UserService service;  
    27.        
    28.     @RequestMapping(value = { "/""/list" }, method = RequestMethod.GET)  
    29.     public String listAllUsers(ModelMap model) {  
    30.     
    31.         List<User> users = service.findAllUsers();  
    32.         model.addAttribute("users", users);  
    33.         return "allusers";  
    34.     }  
    35.        
    36.     @RequestMapping(value = { "/edit-user-{id}" }, method = RequestMethod.GET)  
    37.     public String editUser(@PathVariable int id, ModelMap model) {  
    38.         User user  = service.findById(id);  
    39.         model.addAttribute("user", user);  
    40.         model.addAttribute("edit"true);  
    41.         return "registration";  
    42.     }  
    43.        
    44.     @RequestMapping(value = { "/edit-user-{id}" }, method = RequestMethod.POST)  
    45.     public String updateUser(User user, ModelMap model, @PathVariable int id) {  
    46.         service.updateUser(user);  
    47.         model.addAttribute("success""User " + user.getFirstName()  + " updated successfully");  
    48.         return "success";  
    49.     }  
    50.        
    51.     @RequestMapping(value = { "/delete-user-{id}" }, method = RequestMethod.GET)  
    52.     public String deleteUser(@PathVariable int id) {  
    53.         service.deleteUser(id);  
    54.         return "redirect:/list";  
    55.     }  
    56.        
    57.     @RequestMapping(value = "/Access_Denied", method = RequestMethod.GET)  
    58.     public String accessDeniedPage(ModelMap model) {  
    59.         model.addAttribute("user", getPrincipal());  
    60.         return "accessDenied";  
    61.     }  
    62.    
    63.     @RequestMapping(value = "/login", method = RequestMethod.GET)  
    64.     public String loginPage() {  
    65.         return "login";  
    66.     }  
    67.    
    68.     @RequestMapping(value="/logout", method = RequestMethod.GET)  
    69.     public String logoutPage (HttpServletRequest request, HttpServletResponse response) {  
    70.         Authentication auth = SecurityContextHolder.getContext().getAuthentication();  
    71.         if (auth != null){      
    72.             new SecurityContextLogoutHandler().logout(request, response, auth);  
    73.         }  
    74.         return "redirect:/login?logout";  
    75.     }  
    76.    
    77.     private String getPrincipal(){  
    78.         String userName = null;  
    79.         Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();  
    80.    
    81.         if (principal instanceof UserDetails) {  
    82.             userName = ((UserDetails)principal).getUsername();  
    83.         } else {  
    84.             userName = principal.toString();  
    85.         }  
    86.         return userName;  
    87.     }  
    88.    
    89. }  



    项目代码将在文章最后提供。

    不部署 & 运行

    下载本文末尾的项目代码 在一个 Servlet 3.0 容器中发布本应用. 在这里我使用的是tomcat
    打开浏览器访问 http://localhost:8080/SpringSecurityMethodLevelSecurityAnnotationExample/, 将被转到登录界面. 填入 USER 权限的证书。


    提交表单,能够看到用户列表


    尝试删除用户,就会转到 访问拒绝页面因为USER 角色没有删除权限。



    ADMIN角色的账户登录


    提交表单将看到用户列表页面


    编辑第一行 带有“admin”权限的用户



    回到用户列表界面

    编辑一个带有dba角色的账户



    访问拒绝的原因是带有@PostAuthorize 注解的findById 方法,带有Spring EL表单式限制只有dba角色的用户才可以调用。

    只能够删除dba角色的账户,删除其他账户都会出现访问拒绝页面。



    退出然后用拥有DBA角色的账户登录  [dba,root123],点击第一个用户的删除链接。这个用户将被成功删除掉。



    项目源码下载地址:http://websystique.com/?smd_process_download=1&download_id=1475

  • 相关阅读:
    设计一个圆柱体类,计算表面积及体积。建立一个半径为3、高为3.5的圆柱体,输出其表面积及体积
    写一个方法完成如下功能,判断从文本框textbox1输入的一个字符,如果是数字则求该数字的阶乘,如果是小写字条,则转换为大写,大写字符不变,结果在文本框textbox2中显示
    写一方法用来计算1+2+3+...n,其中n作为参数输入,返回值可以由方法名返回,也可以由参数返回
    winform控件记录
    写4个同名方法,实现两个整数、两个实数,一个实数一个整数,一个整数一个实数之间的求和。在主调函数中调用这4个方法计算相关的值。(方法的重载)
    写一方法计算实现任意个整数之和.在主调函数中调用该函数,实现任意个数之和。(使用params参数)
    在主函数中提示用户输入用户名和密码。另写一方法来判断用户输入是否正确。该方法分别返回一个bool类型的登录结果和和一个string类型的登录信息。如登录成功,返回true及“登录成功”,若登录失败则返回false及“用户名错误”或“密码错误”(使用out参数)
    Linux下使用Kickstart自动化安装平台架构
    Day10 多线程理论 开启线程
    关闭ipv6的方法
  • 原文地址:https://www.cnblogs.com/jpfss/p/8668220.html
Copyright © 2011-2022 走看看