微人事第十天:spring security初体验

Spring Security 是 Spring 家族中的一个安全管理框架,实际上,在 Spring Boot 出现之前,Spring Security 就已经发展了多年了,但是使用的并不多,安全管理这个领域,一直是 Shiro 的天下。

相对于 Shiro,在 SSM/SSH 中整合 Spring Security 都是比较麻烦的操作,所以,Spring Security 虽然功能比 Shiro 强大,但是使用反而没有 Shiro 多(Shiro 虽然功能没有 Spring Security 多,但是对于大部分项目而言,Shiro 也够用了)。

自从有了 Spring Boot 之后,Spring Boot 对于 Spring Security 提供了 自动化配置方案,可以零配置使用 Spring Security。

因此,一般来说,常见的安全管理技术栈的组合是这样的:

SSM + Shiro
Spring Boot/Spring Cloud + Spring Security

1.创建工程
添加web和spring security依赖
在这里插入图片描述
可以看到pom.xml文件中web和security已经被引入进来。
在这里插入图片描述
只要加了spring security依赖,项目中的所有接口都被保护起来了。
2.编写接口并进行测试

package org.javaboy.security;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController  {

    @GetMapping("/hello")
    public String hello() {
        return "hello security";
    }
}

访问路径:http://localhost:8080/hello
跳转到登陆界面,这是因为加了spring security,项目中所有的接口就被保护起来了。
在这里插入图片描述
查看控制可以看到登陆密码:
密码是项目启动后随机生成的
在这里插入图片描述
登陆的用户名默认是user,点击登陆后可以看到页面跳转成功
在这里插入图片描述
spring security的使用非常的方便,只需要在pom.xml加入依赖,就可以把接口保护起来了。

虽然现在spring security生效了,但是密码是随机生成的非常繁琐,接下来我们要自定义用户名和密码。自定义用户名和密码可以在数据库中配置也可以在配置文件中配置,接下我们使用配置文件的方式来自定义用户名和密码。

通过配置文件来配置密码
在application.properties中分别配置登陆的密码,用户名和角色(这里的角色是管理员)。

spring.security.user.password=123
spring.security.user.name=javaboy
spring.security.user.roles=admin

现在重新启动项目,访问路径:http://localhost:8080/hello,现在控制台不会再生成随机密码了,输入配置的用户名和密码,跳转成功:
在这里插入图片描述
以上是由配置文件来配置,接下来还有另一种配置方式

java代码配置用户名和密码
正常情况下直接在代码中写密码是不行的,因为密码需要加密。这里为了方便,通过@Bean告诉系统不必加密(虽然这种方式已经过时)

package org.javaboy.security.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    //告诉系统不加密
    @Bean
    PasswordEncoder passwordEncoder() {
        return NoOpPasswordEncoder.getInstance();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("javaboy").password("123").roles("admin")
                .and()
                .withUser("江南一点雨").password("456").roles("user");
    }
}

启动重启访问路径http://localhost:8080/hello 输入两种不同的用户名和密码都能跳转成功。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值