博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
使用SpringSecurity
阅读量:7142 次
发布时间:2019-06-29

本文共 6296 字,大约阅读时间需要 20 分钟。

前几天写了一个SpringBoot对拦截器的使用,在实际项目中,对一些情况需要做一些安全验证,比如在没有登录的情况下访问特定的页面应该解释的拦截处理。这一篇介绍使用SpringSecurity来做简单的安全控制,由于SpringSecurity比较复杂,如果有不对的地方可以大家一起学习。

新建项目,前端页面使用thymeleaf,加入security依赖,pom文件如下:

4.0.0
com.dalaoyang
springboot_security
0.0.1-SNAPSHOT
jar
springboot_security
springboot_security
org.springframework.boot
spring-boot-starter-parent
1.5.9.RELEASE
UTF-8
UTF-8
1.8
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-devtools
runtime
org.springframework.boot
spring-boot-starter-test
test
org.springframework.boot
spring-boot-starter-security
net.sourceforge.nekohtml
nekohtml
1.9.15
org.springframework.boot
spring-boot-starter-thymeleaf
org.springframework.boot
spring-boot-maven-plugin
复制代码

配置文件本文就是将之前整合thymeleaf的配置拿了过来,代码如下:

##端口号server.port=8888##去除thymeleaf的html严格校验spring.thymeleaf.mode=LEGACYHTML5#设定thymeleaf文件路径 默认为src/main/resources/templatesspring.freemarker.template-loader-path=classpath:/templates#设定静态文件路径,js,css等spring.mvc.static-path-pattern=/static/**# 是否开启模板缓存,默认true# 建议在开发时关闭缓存,不然没法看到实时页面spring.thymeleaf.cache=false# 模板编码spring.freemarker.charset=UTF-8复制代码

接下来是这篇文章重要的地方,新建一个SecurityConfig类,继承WebSecurityConfigurerAdapter类,重写configure(HttpSecurity httpSecurity)方法,其中/css/**和/index的资源不需要验证,直接可以请求,/user/**的资源需要验证,权限是USER,/admin/**的资源需要验证,权限是ADMIN,登录地址是/login,登录失败地址是/login_error,异常重定向到 /401,注销跳转到/logout。 注入AuthenticationManagerBuilder,在内存中创建一个用户dalaoyang,密码123的用户,权限是USER,代码如下:

package com.dalaoyang.config;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.context.annotation.Configuration;import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;import org.springframework.security.config.annotation.web.builders.HttpSecurity;import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;/** * @author dalaoyang * @Description * @project springboot_learn * @package com.dalaoyang.config * @email yangyang@dalaoyang.cn * @date 2018/4/28 */@EnableWebSecuritypublic class SecurityConfig extends WebSecurityConfigurerAdapter {    // /css/**和/index的资源不需要验证,直接可以请求    // /user/**的资源需要验证,权限是USER /admin/**的资源需要验证,权限是ADMIN    // 登录地址是/login 登录失败地址是 /login_error    // 异常重定向到 /401    // 注销跳转到 /logout    @Override    protected void configure(HttpSecurity httpSecurity) throws Exception{        httpSecurity                .authorizeRequests()                .antMatchers("/css/**","/index").permitAll()                .antMatchers("/user/**").hasRole("USER")                .antMatchers("/admin/**").hasRole("ADMIN")                .and()                .formLogin().loginPage("/login").failureUrl("/login_error")                .and()                .exceptionHandling().accessDeniedPage("/401");        httpSecurity.logout().logoutSuccessUrl("/logout");    }    //内存中创建用户,用户名为dalaoyang,密码123,权限是USER    @Autowired    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {        auth                .inMemoryAuthentication()                .withUser("dalaoyang").password("123").roles("USER");    }}复制代码

创建一个TestController负责跳转,代码如下:

package com.dalaoyang.controller;import org.springframework.stereotype.Controller;import org.springframework.ui.Model;import org.springframework.web.bind.annotation.RequestMapping;/** * @author dalaoyang * @Description * @project springboot_learn * @package com.dalaoyang.controller * @email yangyang@dalaoyang.cn * @date 2018/4/28 */@Controllerpublic class TestController {    @RequestMapping("/")    public String index(){        return "index";    }    @RequestMapping("/index")    public String index2(){        return "index";    }    @RequestMapping("/user")    public String user(){        return "user/index";    }    @RequestMapping("/admin")    public String admin(){        return "admin/index";    }    @RequestMapping("/login")    public String login(){        return "login";    }    @RequestMapping("/login_error")    public String login_error(Model model){        model.addAttribute("login_error", "用户名或密码错误");        return "login";    }    @RequestMapping("/logout")    public String logout(Model model){        model.addAttribute("login_error", "注销成功");        return "login";    }    @RequestMapping("/401")    public String error(){        return "401";    }}复制代码

创建一个user/index.html,用于校验USER权限,没有登录的话不能直接访问,代码如下:

    
user/indexuser/index
复制代码

创建一个admin/index.html,只允许ADMIN权限访问,代码如下:

    
adminadmin/index复制代码

401页面,用于没有权限跳转:

    
401401复制代码

index页面,任何权限都能访问

    
indexindex复制代码

login页面,用于登录

    
login

login

用户名
密码
复制代码

到这里就全部创建完成了,启动项目,访问,如图,可以直接访问。

访问被拦截到http://localhost:8888/login,如图

先输入错误的密码,如图

然后输入用户名dalaoyang密码123,点击登录结果如图

访问,如图,没有权限

我们在回到http://localhost:8888/user点击注销,如图

源码下载 :

个人网站:

转载地址:http://pnwgl.baihongyu.com/

你可能感兴趣的文章
机器学习中的正则化和范数规则化
查看>>
C#修改文件或文件夹的权限,为指定用户、用户组添加完全控制权限
查看>>
Datazen自定义地图
查看>>
Calculate CRC32 as in STM32 hardware (EWARM v.5.50 and later)
查看>>
Android Sdk 国内镜像下载地址
查看>>
C#学习笔记(八):扩展方法
查看>>
【算法导论】多项式求和
查看>>
DELPHI关闭瑞星监控的源代码
查看>>
poj 2762 Going from u to v or from v to u? (推断它是否是一个薄弱环节图)
查看>>
web网站加速之CDN(Content Delivery Network)技术原理
查看>>
IndexReader已解决的问题
查看>>
servlet其工作原理和例子证明
查看>>
document.all使用
查看>>
BZOJ4044 : [Cerc2014] Virus synthesis
查看>>
动态链接库、静态链接库
查看>>
mysql日志问题定位实用命令
查看>>
【LeetCode】257. Binary Tree Paths
查看>>
MySQL SQL优化之in与range查询【转】
查看>>
jQuery 有条件排序
查看>>
有趣html5(两)----使用canvas结合剧本画在画布上的简单图(html5另一个强大)...
查看>>