Spring Security实战(一)认证、授权以及权限控制

之前写过一篇Shiro的,讲解了Shiro的基础用法。本来想做一个系列,但是忙别的去了,一直没搞。由于项目需求,抽空学了一下 Security,分享一些经验和大家共同学习一下

本节目标

搭建一个简单的Web 工程实现以下功能

  1. 简单的认证、授权功能
  2. 权限控制(URL匹配的权限控制,方法权限控制,基于Thymeleaf的页面按钮权限)

Demo 技术选型

SpringBoot 2.1.6.RELEASE + Spring Security + JdbcTemplate + Thymeleaf

Security 如何工作

图片.png

和Shiro一样,Security 以过滤器的形式集成到我们的项目中,帮助我们管理用户的权限。本文不做过多原理方面的分析,后续如果有续集为大家讲解

集成Security

在SpringBoot的基础上添加依赖即可
build.gradle

dependencies {
    ...
    compile("org.springframework.boot:spring-boot-starter-security")
    ...
}

pom.xml

<dependencies>
    ...
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
    ...
</dependencies>

但这还远远不够,想要完成我们的需求,还需要做一些工作

简单的认证、授权

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/", "/home").permitAll()
                .anyRequest().authenticated()
                .and()
            .formLogin()
                .loginPage("/login")
                .permitAll()
                .and()
            .logout()
                .permitAll();
    }

    @Bean
    @Override
    public UserDetailsService userDetailsService() {
        UserDetails user =
             User.withDefaultPasswordEncoder()
                .username("user")
                .password("123456")
                .roles("USER")
                .build();

        return new InMemoryUserDetailsManager(user);
    }
}

@EnableWebSecurity启用Spring Security 对Web的支持并与SpringMVC集成,中间的过程我们无需关心

再看看上面代码,我们都做了什么?

了解过Shiro的朋友,看到上面的代码是不是感觉很熟悉?

  • 首先是URL配置,我们配置 "/""home" 无需任何访问权限,其余的请求需要授权,并配置了登录和注销

  • 我们还需要提供一个 UserDetailsService 的实现来提供用户的认证和授权,上述代码提供了一个简单的基于内存的UserDetailsManager,实际开发中,我们可以自己实现一个UserDetailsService ,下文中会有。


Security 会使用 UsernamePasswordAuthenticationFilter、LogoutFilter 来处理我们的登录和注销请求,默认的登录注销路径为"/login""/logout"我们只提供用户的认证和授权信息即可


这个时候为了方便我们看效果,再添加几个页面

  • home.html,所有人可见
    src/main/resources/templates/home.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="https://www.thymeleaf.org" xmlns:sec="https://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
    <head>
        <title>Spring Security Example</title>
    </head>
    <body>
        <h1>Welcome!</h1>

        <p>Click <a th:href="@{/hello}">here</a> to see a greeting.</p>
    </body>
</html>
  • hello.html,根据上面的配置这个页面是需要认证后才可以访问的
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="https://www.thymeleaf.org"
      xmlns:sec="https://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
    <head>
        <title>Hello World!</title>
    </head>
    <body>
        <h1 th:inline="text">Hello [[${#httpServletRequest.remoteUser}]]!</h1>
        <form th:action="@{/logout}" method="post">
            <input type="submit" value="Sign Out"/>
        </form>
    </body>
</html>
  • login.html
    其实Security默认为我们提供了一个登录页面,但是为了加深印象,这里我们自己写一个
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="https://www.thymeleaf.org"
      xmlns:sec="https://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
    <title>Spring Security Example </title>
</head>
<body>
<div th:if="${param.error}">
    Invalid username and password.
</div>
<div th:if="${param.logout}">
    You have been logged out.
</div>
<form th:action="@{/login}" method="post">
    <div><label> User Name : <input type="text" name="username"/> </label></div>
    <div><label> Password: <input type="password" name="password"/> </label></div>
    <div><input type="submit" value="Sign In"/></div>
</form>
</body>
</html>
  • 最后配置一下URL和模板的映射
@Configuration
public class MvcConfig implements WebMvcConfigurer {

    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/home").setViewName("home");
        registry.addViewController("/").setViewName("home");
        registry.addViewController("/hello").setViewName("hello");
        registry.addViewController("/login").setViewName("login");
    }

}

OK 到这里,简单的认证、授权、还有注销完成了

默认情况下,Security登录后会重定向到上一次请求的URL

上述案例源码:
https://github.com/TavenYin/security-example/tree/master/simple-example

关于 UserDetailsService

上述的案例使用的 InMemoryUserDetailsManager,我们在实际开发时不可能使用的。在使用Shiro的时候通常我们会在数据库中拉取用户的认证和授权信息,Security同理

我们自己实现一个 UserDetailsService,权限和角色这里我偷懒了,就没有从数据库拉

public class MyUserDetailsService implements UserDetailsService {
    private static final String ROLE_PREFIX = "ROLE_";
    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserDO user = null;
        try {
            user = jdbcTemplate.queryForObject(Sql.loadUserByUsername, Sql.newParams(username), new BeanPropertyRowMapper<>(UserDO.class));
        } catch (DataAccessException e) {
            e.printStackTrace();
        }

        if (user == null)
            throw new UsernameNotFoundException("用户不存在:" + username);

        return User.builder()
                .username(username)
                .password(user.getPassword()) // 这里的密码是加密后
                .authorities(
                        ROLE_PREFIX +"super_admin",
                        ROLE_PREFIX +"user",
                        "sys:user:add", "sys:user:edit", "sys:user:del",
                        "sys:match", "sys:mm"
                )// 这里偷懒写死几个权限和角色
                .build();
    }

}

并将我们这个新的 UserDetailsService 注册到Security中,并指定密码的加密规则

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/", "/home").permitAll()
                .anyRequest().authenticated()
                .and()
            .formLogin()
                .loginPage("/login")
                .permitAll()
                .and()
            .logout()
                .permitAll();
    }

    @Bean
    @Override
    public UserDetailsService userDetailsService() {
        return new MyUserDetailsService();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService()).passwordEncoder(new BCryptPasswordEncoder());
    }

}

Shiro中角色和权限是分开的,但是在Security中存储在一个集合中,角色以 ROLE_ 开头

权限控制

当用户完成了认证,授权之后,通常我们的接口也是有自己的权限的,只有用户的权限匹配上了才可以访问

  • 对匹配的URL设置权限
    还是上面的configure方法,和Shiro的配置方式很相似
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/", "/home").permitAll()
                // 测试配置URL权限
                .antMatchers("/match/**").hasAuthority("sys:match")
                // 对某URL添加多个权限,可以多次配置
                .antMatchers("/match/**").hasAuthority("sys:mm")
                .anyRequest().authenticated()
                .and()
            .formLogin()
                .loginPage("/login")
                .permitAll()
                .and()
            .logout()
                .permitAll()
                .and()
        ;
    }
  • 方法权限 (可用于接口权限)
    通过@EnableGlobalMethodSecurity,启用注解
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true) // 启用@PreAuthorize
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
}

需要控制权限的方法上添加注解,@PreAuthorize 还可以使用其自带的方法进行校验

    @PreAuthorize("hasRole('user')")
    public Object user() {
        User user = SecurityUtils.currentUser();
        return "OK, u can see it. " + user.getUsername();
    }

Security 还支持其他的方法权限注解,感兴趣的同学可以到 @EnableGlobalMethodSecurity 类里看一下

  • 页面权限控制
    添加依赖
<dependency>
    <groupId>org.thymeleaf.extras</groupId>
    <artifactId>thymeleaf-extras-springsecurity5</artifactId>
</dependency>
<div sec:authorize="hasRole('super_admin')">
    super_admin 可见
</div>

<div sec:authorize="hasAuthority('sys:mm')">
    sys:mm 可见
</div>

更多用法参考:https://github.com/thymeleaf/thymeleaf-extras-springsecurity

权限测试这块写了一点demo,但是有点乱,有想参考的朋友可以看一下
https://github.com/TavenYin/taven-springboot-learning/tree/master/spring-security

参考资料

https://spring.io/guides/gs/securing-web/
https://spring.io/guides/topicals/spring-security-architecture/

计划下一篇为大家带来,Security 认证、注销的自定义扩展

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 157,198评论 4 359
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 66,663评论 1 290
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 106,985评论 0 237
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,673评论 0 202
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 51,994评论 3 285
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,399评论 1 211
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,717评论 2 310
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,407评论 0 194
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,112评论 1 239
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,371评论 2 241
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 31,891评论 1 256
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,255评论 2 250
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 32,881评论 3 233
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,010评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,764评论 0 192
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,412评论 2 269
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,299评论 2 260

推荐阅读更多精彩内容