Springboot整合SpringSecurity 01-使用入门

Springboot整合SpringSecurity 01-使用入门

Spring Security是Spring旗下的一个安全管理框架,使用起来非常方便。
本文参考自Spring Security官方文档:
https://docs.spring.io/spring-security/site/docs/5.1.6.RELEASE/reference/htmlsingle/#preface

本系列的按顺序写的,如果对于某些代码不清楚,请看下前面的几篇文章。
Springboot整合SpringSecurity 01-使用入门
Springboot整合SpringSecurity 02-使用自定义登陆页面
Springboot整合SpringSecurity 03-访问权限控制
Springboot整合SpringSecurity 04-启用登出logout功能
Springboot整合SpringSecurity 05-使用JDBC实现认证和授权
Springboot整合SpringSecurity 06-登陆扩展之自定义登陆验证逻辑
Springboot整合SpringSecurity 07-方法访问权限控制

为了简化配置,本文使用Springboot整合依赖。

1. 引入依赖

<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
        <version>2.0.3.RELEASE</version>
    </parent>
    
    <dependencies>
		<dependency>
		            <groupId>org.springframework.boot</groupId>
		            <artifactId>spring-boot-starter-security</artifactId>
		        </dependency>
		        <dependency>
		            <groupId>org.springframework.boot</groupId>
		            <artifactId>spring-boot-starter-web</artifactId>
		        </dependency>
		        <dependency>
		            <groupId>org.springframework.boot</groupId>
		            <artifactId>spring-boot-starter-thymeleaf</artifactId>
		        </dependency>
        </dependencies>

2.配置application.yml

server:
  port: 10022
  servlet:
    context-path: /security
spring:
  mvc:
    view:
      suffix: .html
      prefix: templates/
    static-path-pattern: /static/**
  thymeleaf:
    prefix: classpath:/templates/

配置项目的path和springmvc的前缀,后缀和静态资源路径以及thymeleaf模板的目录位置

3. 开启webSecurity以及注入初始用户

@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter  {

    @Bean
    @Override
    public UserDetailsService userDetailsService() {
        InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
        manager.createUser(User.withDefaultPasswordEncoder().username("user")
                .password("user").roles("USER").build());
        return manager;
    }
}

为了简化学习,我们使用内存管理用户的账号和密码。这里我们创建了一个user/user的用户,他的roles是USER。

4.创建一个简单的Controller

@Controller
public class HelloController {

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

这里面创建一个测试的接口,用来等下我们访问。

5.创建测试的hello.html页面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Hello World</title>
</head>
<body>
    <h1>This is the First Page Of My Security Project</h1>
</body>
</html>

在resources/templates目录里面创建一个html用来访问。

6.运行项目开始测试。

是的,就这么简单就已经搭建好了一个简单的项目。
启动后,访问

http://localhost:10022/security/hello

就会跳转到SpringSecurity自带的登陆页面。

输入账号密码user/user之后成功跳转到hello.html。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值