二、SpringSecurity+auth2.0系列(form 表单模式)

此模块基于模块一,读者可阅读本专栏

Form 表单模式 适合于传统模式项目 前端和后端都是我们java开发
修改配置完整代码如下

package com.thunisoft.spring_security.config;

import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.server.ErrorPage;
import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpStatus;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
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;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.stereotype.Component;

@Component
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        /**
         * 新增 HttpSecurity基础配置配置
         */
        // http.authorizeRequests().antMatchers("/**").fullyAuthenticated().and().httpBasic();


        /**
         * 新增HttpSecurity formLogin模式
         */
        //http.authorizeRequests().antMatchers("/**").fullyAuthenticated().and().formLogin();
        http.authorizeRequests().antMatchers("/addMember").hasAnyAuthority("addMember")
                .antMatchers("/delMember").hasAnyAuthority("delMember")
                .antMatchers("/showMember").hasAnyAuthority("showMember")
                .antMatchers("/editMember").hasAnyAuthority("editMember").
               // antMatchers("/**").fullyAuthenticated().and().formLogin()
                antMatchers("/login").permitAll().antMatchers("/**").fullyAuthenticated().and().formLogin()
                .loginPage("/login").and().csrf().disable();

    }


    /*
    * 新增授权账户
    * */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //新增一个用户为orange和admin用户,权限不一样
        auth.inMemoryAuthentication().withUser("admin").password("admin").authorities("addMember","delMember","editMember","showMember");
        auth.inMemoryAuthentication().withUser("orange").password("orange").authorities("showMember");
    }


    /**
     * 密码不做任何处理
     * @return
     */
    @Bean
    public static NoOpPasswordEncoder passwordEncoder(){
        return (NoOpPasswordEncoder) NoOpPasswordEncoder.getInstance();
    }





}

配置权限策略
在企业管理系统平台中,会拆分成n多个不同的账号,
每个账号对应不同的接口访问权限,
比如
账号admin所有接口都可以访问;
orange账户 只能访问/addMember接口;
代码如上代码中所示

如何修改403权限不足页面
在config包下新建配置类,代码如下

package com.thunisoft.spring_security.config;


import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.server.ErrorPage;
import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;

@Configuration
public class WebServerAutoConfiguration {
    /**
     * 授权失败调转页面
     * @return
     */
    @Bean
    public ConfigurableServletWebServerFactory webServerFactory() {
        TomcatServletWebServerFactory factory = new TomcatServletWebServerFactory();
        ErrorPage errorPage400 = new ErrorPage(HttpStatus.BAD_REQUEST, "/error/400");
        ErrorPage errorPage401 = new ErrorPage(HttpStatus.UNAUTHORIZED, "/error/401");
        ErrorPage errorPage403 = new ErrorPage(HttpStatus.FORBIDDEN, "/error/403");
        ErrorPage errorPage404 = new ErrorPage(HttpStatus.NOT_FOUND, "/error/404");
        ErrorPage errorPage415 = new ErrorPage(HttpStatus.UNSUPPORTED_MEDIA_TYPE, "/error/415");
        ErrorPage errorPage500 = new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/error/500");
        factory.addErrorPages(errorPage400, errorPage401, errorPage403, errorPage404, errorPage415, errorPage500);
        return factory;
    }
}

在controller包下新建errorcontroller类
代码如下:

package com.thunisoft.spring_security.controller;


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

@RestController
public class ErrorController {



    @RequestMapping("/error/403")
    public String error403() {
        return "您当前访问的接口权限不足!";
    }


    @RequestMapping("/error/400")
    public String error400() {
        return "您当前请求异常!";
    }

    @RequestMapping("/error/401")
    public String error401() {
        return "您的状态未认证!";
    }

    @RequestMapping("/error/404")
    public String error404() {
        return "页面未查询到!";
    }

    @RequestMapping("/error/415")
    public String error415() {
        return "请求格式错误!";
    }

    @RequestMapping("/error/500")
    public String error500() {
        return "服务器内部错误!";
    }

}

登陆页面
包controller新建登录类
代码如下

package com.thunisoft.spring_security.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class LoginController {
    @RequestMapping("/login")
    public String login() {
        return "login";
    }
}

导入freemarker依赖

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

自定义登录页面login.ftl
在resource下新建templates,新建这个文件

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html;
            charset=ISO-8859-1">
    <title>Insert title here</title>
</head>
<body>

<h1>权限控制登陆系统</h1>
<form action="/login" method="post">
    <span>用户名称</span><input type="text" name="username"/> <br>
    <span>用户密码</span><input type="password" name="password"/> <br>
    <input type="submit" value="登陆">

</form>

<#if RequestParameters['error']??>
用户名称或者密码错误
</#if>
</body>
</html>

配置application.yml
次数为配置页面的参数

spring:
  freemarker:
    settings:
      classic_compatible: true
      datetime_format: yyy-MM-dd HH:mm
      number_format: 0.##
    suffix: .ftl
    template-loader-path: classpath:/templates

运行项目,进行登录测试

使用 Spring Security OAuth2.0 实现授权登录的步骤如下: 1. 添加 Spring Security OAuth2.0 依赖:在 `pom.xml` 文件中添加以下依赖: ```xml <dependency> <groupId>org.springframework.security.oauth</groupId> <artifactId>spring-security-oauth2</artifactId> <version>2.3.4.RELEASE</version> </dependency> ``` 2.一个实体类 `User`,用来示用户信息,包括 `id`、`username`、`password`、`roles` 等信息。 3.一个 `UserDetailsService` 接口的实现类 `UserDetailsServiceImpl`,用来从数据库中获取用户信息,并返回一个 `UserDetails` 对象。 ```java @Service public class UserDetailsServiceImpl implements UserDetailsService { @Autowired private UserRepository userRepository; @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { User user = userRepository.findByUsername(username); if (user == null) { throw new UsernameNotFoundException("用户不存在"); } List<GrantedAuthority> authorities = new ArrayList<>(); for (String role : user.getRoles()) { authorities.add(new SimpleGrantedAuthority(role)); } return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), authorities); } } ``` 4.一个 `AuthorizationServerConfigurerAdapter` 类来配置授权服务器。 ```java @Configuration @EnableAuthorizationServer public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter { @Autowired private AuthenticationManager authenticationManager; @Autowired private UserDetailsService userDetailsService; @Autowired private DataSource dataSource; @Bean public TokenStore tokenStore() { return new JdbcTokenStore(dataSource); } @Override public void configure(ClientDetailsServiceConfigurer clients) throws Exception { clients.jdbc(dataSource); } @Override public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception { endpoints.tokenStore(tokenStore()) .authenticationManager(authenticationManager) .userDetailsService(userDetailsService); } } ``` 5.一个 `WebSecurityConfigurerAdapter` 类来配置 Spring Security。 ```java @Configuration @EnableWebSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private UserDetailsServiceImpl userDetailsService; @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder()); } @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/oauth/**").permitAll() .anyRequest().authenticated() .and() .formLogin().permitAll() .and() .csrf().disable(); } @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } } ``` 6. 在控制器中添加一个请求 `/oauth/authorize`,用来处理授权请求。 ```java @Controller public class AuthorizationController { @RequestMapping("/oauth/authorize") public String authorize() { return "authorize"; } } ``` 7.一个视图 `authorize.html`,用来显示授权界面。该视图中包含一个表单,用来输入用户名和密码。 ```html <!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <title>授权</title> </head> <body> <form th:action="@{/oauth/authorize}" method="post"> <label>用户名:</label> <input type="text" name="username"><br> <label>密码:</label> <input type="password" name="password"><br> <button type="submit">授权</button> </form> </body> </html> ``` 8. 启动应用程序,并访问 `/oauth/authorize`,输入用户名和密码后,将跳转到授权页面,选择授权后,将返回一个授权码或令牌,用于后续的访问。 以上就是使用 Spring Security OAuth2.0 实现授权登录的详细步骤流程。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

@我不是大鹏

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值