SpringSecurity简单创建和使用

简介

一般Web应用的需要进行认证授权

认证:验证当前访问系统的是不是本系统的用户,并且要确认具体是哪个用户

授权:经过认证后判断当前用户是否有权限进行某个操作

准备工作

添加依赖xml

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.5.0</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <optional>true</optional>
    </dependency>
<!--SpringSecurity依赖-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
</dependencies>

创建一个Controller去测试

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
 
@RestController
public class HelloController {

     @ResponseBody
    @RequestMapping("/hello")
    public String hello(){
        return "Hello";
    }
}

引入依赖后我们在尝试去访问之前的接口就会自动跳转到一个SpringSecurity的默认login登陆页面,默认用户名是user,密码会输出在控制台。

可以通过继承 WebSecurityConfigurerAdapter 实现修改默认页面

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests() // 开启权限配置
                .anyRequest()  // 所有请求
                .authenticated() // 进行认证
                .and()
                .formLogin() // 设置表单登录
                .loginPage("/login.html")//修改默认的登入页面,可以替换为自己的登入页面
                .loginProcessingUrl("/doLogin")//处理请求要和form表单里面的action一致
                .defaultSuccessUrl("/index")//登录成功去的地方也可以是请求
                // .successForwardUrl("/index")
                // .failureForwardUrl()
                .failureUrl("/error.html")//登录失败
                .usernameParameter("uname")//获取用户名
                .passwordParameter("passwd")//获取密码
                .permitAll()  // 跟登录相关的页面和接口不做拦截,直接通过
                .and()
                .csrf().disable();  // 禁用CSRF防御功能,Spring Security自带了CSRF防御机制,但是我们这里为了测试方便,先将CSRF防御机制关闭
    }
}

可以在static文件下创建login.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>登录</title>
    <link href="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
    <script src="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>
    <script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<style>
    #login .container #login-row #login-column #login-box {
        border: 1px solid #9C9C9C;
        background-color: #EAEAEA;
    }
</style>
<body>
<div id="login">
    <div class="container">
        <div id="login-row" class="row justify-content-center align-items-center">
            <div id="login-column" class="col-md-6">
                <div id="login-box" class="col-md-12">
                    <form id="login-form" class="form" action="/doLogin" method="post">
                        <h3 class="text-center text-info">登录</h3>
                        <div class="form-group">
                            <label for="username" class="text-info">用户名:</label><br>
                            <input type="text" name="uname" id="username" class="form-control">
                        </div>
                        <div class="form-group">
                            <label for="password" class="text-info">密码:</label><br>
                            <input type="text" name="passwd" id="password" class="form-control">
                        </div>
                        <div class="form-group">
                            <input type="submit" name="submit" class="btn btn-info btn-md" value="登录">
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
</body>

 然后创建一个HelloController的类,就可以开始测试

@RestController
public class HelloController {

   @RequestMapping(index)
    public String index(){
        // 获取登录用户的用户名
        String name = SecurityContextHolder.getContext().getAuthentication().getName();
        return "index "+name;
    }
}

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Security 是一个功能强大且灵活的框架,用于在 Java 应用程序中实现身份验证和授权。以下是一个简单的示例,演示了如何在 Spring Security 中进行基本配置和使用。 首先,在 pom.xml 文件中添加 Spring Security 的依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> ``` 接下来,创建一个配置类来配置 Spring Security。可以创建一个类,并使用 `@EnableWebSecurity` 注解进行标记: ```java @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/public").permitAll() .anyRequest().authenticated() .and() .formLogin().permitAll() .and() .logout().permitAll(); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication() .withUser("admin").password(passwordEncoder().encode("password")).roles("ADMIN") .and() .withUser("user").password(passwordEncoder().encode("password")).roles("USER"); } @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } } ``` 上述配置类中,我们通过 `configure(HttpSecurity http)` 方法定义了 URL 的访问权限规则,并配置了登录和登出行为。通过 `configure(AuthenticationManagerBuilder auth)` 方法,我们在内存中定义了两个用户(admin 和 user)及其密码和角色。 最后,创建一个简单的控制器类来定义一些访问路径。可以使用 `@RestController` 注解来标记该类,并使用 `@RequestMapping` 注解来定义请求路径: ```java @RestController public class HelloController { @RequestMapping("/public") public String publicEndpoint() { return "Public endpoint"; } @RequestMapping("/private") public String privateEndpoint() { return "Private endpoint"; } } ``` 以上示例中,`/public` 路径是公开访问的,而 `/private` 路径需要进行身份验证才能访问。 这只是一个简单的示例,展示了 Spring Security 的基本用法。你可以根据自己的需求进行更复杂的配置和定制化。希望对你有所帮助!如果有更多问题,请继续提问。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值