Spring-Security

一、Spring-Security初识

简介

最近做了一个ssm整合的项目,使用到了Spring-security,在我们之前的web项目在关于用户登录验证总是通过servlte中的session获取其中的user和设置user,现在我们有了框架spring就帮我把这些操作都封装到一个包里面

这是spring-security的核心功能

  • 认证 (你是谁)
  • 授权 (你能干什么)
  • 攻击防护 (防止伪造身份)
    Spring-Security_第1张图片

入门项目

<dependency>
    <groupId>org.springframework.securitygroupId>
    <artifactId>spring-security-testartifactId>
    <scope>testscope>
dependency>    

首先要配置我们的web.xml


<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns="http://java.sun.com/xml/ns/javaee"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
         version="2.5">
  <display-name>SpringSecurity314display-name>

  <context-param>
    <param-name>contextConfigLocationparam-name>
    <param-value>classpath:spring-security.xmlparam-value>
  context-param>
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
  listener>
  <filter>
    <filter-name>springSecurityFilterChainfilter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxyfilter-class>
  filter>
  <filter-mapping>
    <filter-name>springSecurityFilterChainfilter-name>
    <url-pattern>/*url-pattern>
  filter-mapping>
  <welcome-file-list>
    <welcome-file>index.htmlwelcome-file>
    <welcome-file>index.htmwelcome-file>
    <welcome-file>index.jspwelcome-file>
    <welcome-file>default.htmlwelcome-file>
    <welcome-file>default.htmwelcome-file>
    <welcome-file>default.jspwelcome-file>
  welcome-file-list>
web-app>

同时web.xml指定了一个名为spring-security.xml的配置文件,接下来的配置就都是在这个文件中完成的。


<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:security="http://www.springframework.org/schema/security"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security.xsd">
    
    <security:http security="none" pattern="/login.html" />
    <security:http security="none" pattern="/failer.html" />
    <security:http auto-config="true" use-expressions="false" >
        
        <security:intercept-url pattern="/**" access="ROLE_USER" />
        
        <security:form-login login-page="/login.html"
                             login-processing-url="/login" username-parameter="username"
                             password-parameter="password" authentication-failure-url="/failer.html"
                             default-target-url="/success.html" authentication-success-forward-url="/success.html"
        />

        
        <security:csrf disabled="true" />
    security:http>
    <security:authentication-manager>
        <security:authentication-provider>
            <security:user-service>
                <security:user name="user" password="{noop}user"
                               authorities="ROLE_USER" />
                <security:user name="admin" password="{noop}admin"
                               authorities="ROLE_ADMIN" />
            security:user-service>
        security:authentication-provider>
    security:authentication-manager>
beans>

如配置文件所示我们创建了2个用户user,admin

只要我们的项目一启动,Security就开始工作了

二、项目实战

连接数据库配置


<security:http pattern="/login.jsp" security="none"/>
<security:http pattern="/failer.jsp" security="none"/>
<security:http pattern="/css/**" security="none"/>
<security:http pattern="/img/**" security="none"/>
<security:http pattern="/plugins/**" security="none"/>

关于连接数据库的配置


<security:authentication-manager>
    <security:authentication-provider user-service-ref="userService">
        
        <security:password-encoder ref="passwordEncoder"/>
    security:authentication-provider>
security:authentication-manager>


<bean id="passwordEncoder" class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder"/>

userService

public interface UserService extends UserDetailsService {
	//啥也不用干
}

user实现类

@Service("userService")
@Transactional
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        UserInfo userinfo = null;
        userinfo = userDao.findByUsername(s);
        //处理的对象封装成UserDetails
//        User user = new User(userinfo.getUsername(), "{noop}" +userinfo.getPassword(), getAuthority(userinfo.getRoles()));
        User user = new User(userinfo.getUsername(), userinfo.getPassword(), userinfo.getStatus() == 0 ? false : true, true, true, true, getAuthority(userinfo.getRoles()));
        return user;
    }

    private List<SimpleGrantedAuthority> getAuthority(List<Role> roles) {
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
        for (Role role : roles) {
            authorities.add(new SimpleGrantedAuthority("ROLE_"+role.getRoleName()));
        }
        return authorities;
    }
}    

loadUserByUsername根据id查询user返回给Security处理,下面这个函数是我们根据数据库中存储的role格式进行修改

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-WZgIsicZ-1642407664314)(C:\Users\86157\AppData\Local\Temp\1642398962529.png)]

    
    <security:password-encoder ref="passwordEncoder"/>

由于配置了加密方式,所以我们的密码不用加{noop}


<security:logout invalidate-session="true" logout-url="/logout.do" logout-success-url="/login.jsp" />

这是关于退出的代码Security已经帮我们做好了

权限管理

jsr250配置

pom.xml文件

<dependency>
    <groupId>javax.annotationgroupId>
    <artifactId>jsr250-apiartifactId>
    <version>1.0version>
dependency>

首先我们在配置文件中简介配置开始权限控制

<security:global-method-security jsr250-annotations="enabled"/>

然后在我们的servlet中添加注解

我们是通过这个注解实现的@RolesAllowed({“ADMIN”})

@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;


    //给用添加id
    @RolesAllowed({"ADMIN"})
    @RequestMapping("/addRoleToUser.do")
    public String addRoleToUser(@RequestParam(name = "userId",required = true) String userId,@RequestParam( name = "ids",required = true) String[] roleIds){
        userService.addRoleToUser(userId,roleIds);
        return "redirect:findAll.do";
    }
}    

这样就只有具有ADMIN权限的用户才能进行添加操作

@PermitAll表示允许所有的角色进行访问,也就是说不进行权限控制

@DenyAll是和PermitAll相反的,表示无论什么角色都不能访问

除了这个配置还有另一个

secured配置

通过@secured


@Secured注解标注的方法进行权限控制的支持,其值默认为disabled。

@Secured(“ROLE_TELLER”) 这样配置

Spel表达式配置

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-yQGiwrvG-1642407664315)(D:\Ajava技能树\SSM整合\SSM整合案例\企业权限管理系统\day05\资料\4.表达式使用介绍.bmp)]

页面端标签控制权限

在jsp页面中我们可以使用spring security提供的权限标签来进行权限控制

maven导入

       <dependency>
           <groupId>org.springframework.securitygroupId>
           <artifactId>spring-security-taglibsartifactId>
           <version>${spring.security.version}version>
       dependency>

页面导入

<%@taglib uri="http://www.springframework.org/security/tags" prefix="security"%>

  • 用户管理
  • <security:http auto-config="true" use-expressions="false">
        
        <security:intercept-url pattern="/**" access="ROLE_USER,ROLE_ADMIN"/>
    security>
    

    把use-expressions改为true

           
    
           
    

    security:intercept-url pattern="/**" access=“ROLE_USER,ROLE_ADMIN”/>

    
    把use-expressions改为true
    
    
       
    
       
    
    
    

    你可能感兴趣的:(java,spring,java,安全)