SpringBoot整合springsecurity

目录

  • 一、SpringBoot整合SpringSecurity
    • 1、pom文件
    • 2、静态资源
    • 3、MySecurityController
    • 4、自定义SpringSecurity的配置类(重点)

1、pom文件

<dependencies>
    <dependency>
        <groupId>org.thymeleaf.extrasgroupId>
        <artifactId>thymeleaf-extras-springsecurity5artifactId>
    dependency>
    <dependency>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-securityartifactId>
    dependency>
    <dependency>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-thymeleafartifactId>
    dependency>
    <dependency>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-webartifactId>
    dependency>

    <dependency>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-devtoolsartifactId>
        <scope>runtimescope>
        <optional>trueoptional>
    dependency>
    <dependency>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-testartifactId>
        <scope>testscope>
        <exclusions>
            <exclusion>
                <groupId>org.junit.vintagegroupId>
                <artifactId>junit-vintage-engineartifactId>
            exclusion>
        exclusions>
    dependency>
dependencies>

2、静态资源

跳转到目录
SpringBoot整合springsecurity_第1张图片
1.html, 其他x.html都一样
SpringBoot整合springsecurity_第2张图片
welcome.html


<html xmlns:th="http://www.thymeleaf.org"
	  xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title heretitle>
head>
<body>
	<h1 align="center">欢迎光临武林秘籍管理系统h1>
	<div sec:authorize="!isAuthenticated()">
		<h2 align="center">游客您好,如果想查看武林秘籍 <a th:href="@{/userlogin}">请登录a>h2>
	div>
	<div sec:authorize="isAuthenticated()">
		<h2><span sec:authentication="name">span>,您好,您的角色有:
			<span sec:authentication="principal.authorities">span>h2>
		<form th:action="@{/logout}" method="post">
			<input type="submit" value="注销"/>
		form>
	div>
	<hr>
	
	<div sec:authorize="hasRole('vip1')">
		<h3>普通武功秘籍h3>
		<ul>
			<li><a th:href="@{/level1/1}">罗汉拳a>li>
			<li><a th:href="@{/level1/2}">武当长拳a>li>
			<li><a th:href="@{/level1/3}">全真剑法a>li>
		ul>
	div>
	
	<div sec:authorize="hasRole('vip2')">
		<h3>高级武功秘籍h3>
		<ul>
			<li><a th:href="@{/level2/1}">太极拳a>li>
			<li><a th:href="@{/level2/2}">七伤拳a>li>
			<li><a th:href="@{/level2/3}">梯云纵a>li>
		ul>
	div>
	
	<div sec:authorize="hasRole('vip3')">
		<h3>绝世武功秘籍h3>
		<ul>
			<li><a th:href="@{/level3/1}">葵花宝典a>li>
			<li><a th:href="@{/level3/2}">龟派气功a>li>
			<li><a th:href="@{/level3/3}">独孤九剑a>li>
		ul>
	div>

body>
html>

login.html


<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Insert title heretitle>
head>
<body>
	<h1 align="center">欢迎登陆武林秘籍管理系统h1>
	<hr>
	<div align="center">
		<form th:action="@{/userlogin}" method="post">
			用户名:<input name="user"/><br>
			密码:<input name="pwd"><br/>
			<input type="checkbox" name="remeber"> 记住我<br/>
			<input type="submit" value="登陆">
		form>
	div>
body>
html>

3、MySecurityController

跳转到目录

@Controller
public class MySecurityController {
    private final String PREFIX = "pages/";

    /**
     * 欢迎页
     *
     * @return
     */
    @GetMapping("/")
    public String index() {
        return "welcome";
    }

    /**
     * 登陆页
     *
     * @return
     */
    @GetMapping("/userlogin")
    public String loginPage() {
        return PREFIX + "login";
    }


    /**
     * level1页面映射
     *
     * @param path
     * @return
     */
    @GetMapping("/level1/{path}")
    public String level1(@PathVariable("path") String path) {
        return PREFIX + "level1/" + path;
    }

    /**
     * level2页面映射
     *
     * @param path
     * @return
     */
    @GetMapping("/level2/{path}")
    public String level2(@PathVariable("path") String path) {
        return PREFIX + "level2/" + path;
    }

    /**
     * level3页面映射
     *
     * @param path
     * @return
     */
    @GetMapping("/level3/{path}")
    public String level3(@PathVariable("path") String path) {
        return PREFIX + "level3/" + path;
    }
}

4、自定义SpringSecurity的配置类(重点)

跳转到目录

@EnableWebSecurity //开启WebSecurity模式
public class MySecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //super.configure(http);
        //定制请求的授权规则
        // 不同的角色可以访问的权限不同
        http.authorizeRequests().antMatchers("/").permitAll()
                .antMatchers("/level1/**").hasRole("vip1")
                .antMatchers("/level2/**").hasRole("vip2")
                .antMatchers("/level3/**").hasRole("vip3");

        //开启自动配置的登陆功能,效果,如果没有登陆,没有权限就会来到登陆页面
        //1/login来到登陆页
        //2、重定向到/login?error表示登陆失败
        //3、更多详细规定
        //4、默认post形式的 /login代表处理登陆
        //5、一但定制loginPage;那么 loginPage的post请求 /userlogin就代表处理登陆
        http.formLogin().usernameParameter("user").passwordParameter("pwd")
                .loginPage("/userlogin");



        //开启自动配置的注销功能。
        //1、访问 /logout 表示用户注销,清空session
        //2、注销成功会返回 /login?logout 页面;
        http.logout().logoutSuccessUrl("/");//设置注销成功以后来到首页


        //开启记住我功能
        //登陆成功以后,将cookie发给浏览器保存,以后访问页面带上这个cookie,只要通过检查就可以免登录
        //点击注销会删除cookie
        http.rememberMe().rememberMeParameter("remeber");
    }

    //定义认证规则
    // 需要对密码进行加密 PasswordEncoder
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        // 这些数据正常应该从数据库中读
        // 给不同的用户设置不同的角色
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                .withUser("zhangsan").password(new BCryptPasswordEncoder().encode("123")).roles("vip2", "vip3")
                .and()
                .withUser("lisi").password(new BCryptPasswordEncoder().encode("123")).roles("vip1")
                .and()
                .withUser("zy").password(new BCryptPasswordEncoder().encode("123")).roles("vip1", "vip2", "vip3");

    }
}

你可能感兴趣的:(shiro,SpringBoot,security,SpringSecurity,安全,权限)