欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

SpringSecurity的使用(入门Demo)

程序员文章站 2024-03-19 13:40:22
...

概述:Spring Security的前身是Acegi Security,是Spring项目组中用来提供安全认证服务的框架
认证: 验证用户名密码是否正确的过程,authentication
授权: 对用户所能访问的资源进行控制,authority

tip:

​ 1.SpringSecurity默认情况下不允许使用数据库明文密码,因此当删除<security:password-encoder ref=“passwordEncoder”></security:password-encoder>密码加密后,需要在UserDetailsServiceImpl的loadUserByUsername方法的return User中,对明文密码进行改造,password = “{noop}” + password;

​ 2.将web项目发布到tomcat上,tomcat启动报错:java.lang.ClassNotFoundException: org.springframework.web.context.ContextLoaderListener===>File–>Project Structure–>左键点击war包,右键点击war包对应的工程–>Put into Output Root

UserDetailsServiceImpl
package com.hitalk.service.security;

import com.hitalk.dao.IUserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.Collection;

@Service("userServiceImpl")
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private IUserDao userDao;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        String password = userDao.findPasswordByUsername(s);
        if (password != null && password.trim().length() > 0) {
            Collection<GrantedAuthority> authorities = new ArrayList<>();
            authorities.add(new SimpleGrantedAuthority("ROLE_USER"));
            authorities.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
            User user = new User(s, password, true, true, true, true, authorities);
            return user;
        }
        return null;
    }
}
spring-security.xml
<?xml version="1.0" encoding="UTF-8" ?>
<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">

    <!--配置不拦截的资源,注意不要把pages目录页配置进来-->
    <security:http pattern="/login.jsp" security="none"/>
    <security:http pattern="/failure.jsp" security="none"/>
    <security:http pattern="/css/**" security="none"/>
    <security:http pattern="/js/**" security="none"/>
    <security:http pattern="/img/**" security="none"/>
    <security:http pattern="/plugins/**" security="none"/>

    <!--配置具体的规则-->
    <security:http auto-config="false" use-expressions="false">
        <!--配置具体的拦截放行规则-->
        <security:intercept-url pattern="/**" access="ROLE_USER,ROLE_ADMIN"/>
        <!--配置具体的表单页面-->
        <!--指定登录页面,指定处理登录请求的url,指定登录成功但是授权失败的页面,
        指定登录成功且授权成功的页面,指定登录失败的页面-->
        <security:form-login login-page="/login.jsp" 
                             username-parameter="username" 
                             password-parameter="password"
                             login-processing-url="/login.do"
                             default-target-url="/login.jsp"
                             authentication-success-forward-url="/success.jsp"
                             authentication-failure-url="/failure.jsp">
        </security:form-login>
        <!--关闭跨域请求,注意少了这一行会一直403-->
        <security:csrf disabled="true"/>
        <!--配置注销用户,logout-url指定处理退出请求的url-->
        <security:logout invalidate-session="true" logout-url="/logout.do"
                         logout-success-url="/login.jsp"></security:logout>
    </security:http>


    <!--配置用户身份信息,从数据源查询-->
    <security:authentication-manager>
        <security:authentication-provider user-service-ref="userServiceImpl">
            <security:password-encoder ref="passwordEncoder"></security:password-encoder>
        </security:authentication-provider>
    </security:authentication-manager>


    <!--配置测试用户身份信息-->
    <!-- <security:authentication-manager>
        <security:authentication-provider>
            <security:user-service>
                <security:user name="admin" password="admin" authorities="ROLE_USER, ROLE_ADMIN"/>
                <security:user name="root" password="root" authorities="ROLE_USER"/>
            </security:user-service>
        </security:authentication-provider>
    </security:authentication-manager>-->
    
    <!--配置密码加密类对象-->
    <bean id="passwordEncoder" class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder"></bean>
</beans>
身份认证html
<!--login.jsp-->
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>login</title>
</head>
<body>
<form action="/login.do" method="post">
    用户名:<input type="text" name="username"/><br/>
    密码:<input type="text" name="password"/><br/>
    提交:<input type="submit" value="提交"/><br/>
</form>
</body>
</html>

<!--success.jsp-->
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>success</title>
</head>
<body>
<h1>login success...</h1>
<a href="/logout.do">退出</a>
</body>
</html>
    
<!--failure.jsp-->
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>failure</title>
</head>
<body>
<h1>login failure ...</h1>
</body>
</html>
web.xml
<!--配置listener-->
<listener>
   <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!--环境加载监听器,默认只能加载WEB-INF目录下的资源,手动指定环境参数的位置-->
<context-param>
   <param-name>contextConfigLocation</param-name>
   <param-value>classpath:applicationContext.xml,classpath:spring-security.xml</param-value>
</context-param>
    
<!--配置SpringSecurity核心过滤器-->
<filter>
   <!--此处springSecurityFilterChain固定写法,不能改变-->
   <filter-name>springSecurityFilterChain</filter-name>
   <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
   <filter-name>springSecurityFilterChain</filter-name>
   <url-pattern>/*</url-pattern>
</filter-mapping>

<!--解决中文乱码-->
<filter>
   <filter-name>CharacterEncodingFilter</filter-name>
   <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
   <init-param>
      <param-name>encoding</param-name>
      <param-value>utf-8</param-value>
   </init-param>
</filter>
<filter-mapping>
   <filter-name>CharacterEncodingFilter</filter-name>
   <url-pattern>/*</url-pattern>
</filter-mapping>
数据库sql
# 创建数据库
create database if not exists test_db character set utf8;
# 使用数据库
use test_db;
# 创建表
create table user(
	id int primary key auto_increment,
    username varchar(20),
    password varchar(60)
);
# 插入一条记录,password=123456
insert into user values(null,'zhangsan','$10$pfEJ45.dKRdWBTu3ogakD.jYLN7R0A2RN9d.9a9mMuJHB6fcAZYSa');
pom.xml
    <properties>
        <spring.version>5.0.2.RELEASE</spring.version>
        <spring.security.version>5.0.1.RELEASE</spring.security.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-web</artifactId>
            <version>${spring.security.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-config</artifactId>
            <version>${spring.security.version}</version>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.17</version>
        </dependency>

        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.tomcat.maven</groupId>
                <artifactId>tomcat7-maven-plugin</artifactId>
                <version>2.2</version>
            </plugin>
        </plugins>
    </build>
相关标签: SpringSecurity

上一篇: API认证

下一篇: WEB安全之:SSRF