springboot-springSecurity 之 http Basic认证 (四)

引言:

HTTP基础认证(BA)是一种简单的认证机制。当一个web客户端需要保护任何web资源的时候,服务器会发送一个带有401状态码(未授权)的HTTP回应,还有类似WWW-Authenticate: Basic realm=”realm here” 的 WWW-Authenticate HTTP头。而浏览器这时候就会弹出一个登录对话框,提示输入用户名和密码。

1. 修改配置

在spring boot项目中实现Spring Security进行http Basic认证非常简单,只需在配置文件中增加 .httpBasic(); 直接配置即可使用

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UrlUserService urlUserService;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .csrf().disable()
                .authorizeRequests()
                .antMatchers(DATA_COLLECT_RAW_URL).permitAll()
                .antMatchers("/login").permitAll()
                .antMatchers("/logout").permitAll()
                .antMatchers("/images/**").permitAll()
                .antMatchers("/js/**").permitAll()
                .antMatchers("/css/**").permitAll()
                .antMatchers("/fonts/**").permitAll()
                .antMatchers("/").permitAll()
                .anyRequest().authenticated()
                .and()
                .sessionManagement()
                .and()
                .logout()
                .and()
                .httpBasic();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

 auth.userDetailsService(urlUserService).passwordEncoder(new PasswordEncoder() {//此处为密码使用md5 进行加密

            @Override
            public String encode(CharSequence rawPassword) {
                return MD5Util.encode((String) rawPassword);
            }

            @Override
            public boolean matches(CharSequence rawPassword, String encodedPassword) {
                return encodedPassword.equals(MD5Util.encode((String) rawPassword));
            }
        });
    }
}

2. 登录方式的变化

http Basic 实际上就是将我门的用户名和密码连接起来然后 使用base64进行加密,将加密后的密文放在http 的header 中进行验证。

帐号密码加密如下 (假设账号密码都为admin)

admin:admin    base64 加密后为     YWRtaW46YWRtaW4=
加密后的串放入 header 时应在拼结为 
Basic YWRtaW46YWRtaW4=       

注意:Basic  与密码串之间为一个空格  

postMan 请求如下:

这里写图片描述

3.在controller 中获取请求参数

由于登录是security 进行验证的,验证成功后会跳转到 “/login“ api,所以我门要定义自己login api

@AuthenticationPrincipal 注解是为了从security 中获取登录后的user 信息。
登录成功后返回用户信息。
当登出后也会进入”/login” api ,登出成功返回null

@RequestMapping(value = "/login")
    @ResponseBody
    //用户名密码是用base64 加密 原文为 admin:admin 即 用户名:密码  内容是放在request.getHeader 的 "authorization" 中
    public Object login(@AuthenticationPrincipal User loginedUser, @RequestParam(name = "logout", required = false) String logout) {
        if (logout != null) {
            return null;
        }
        if (loginedUser != null) {
            return loginedUser;
        }
        return null;
    }

关于security 的Http Basic 验证到此就告一段落了。敬请期待。

  • 5
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
Spring Security 是一个企业级安全框架,它提供了一系列的安全服务和基于标准的安全注解,帮助开发者在应用程序中实现身份认证和权限控制等功能。Spring Boot 是一个快速构建应用程序的框架,它提供了对 Spring 框架的自动配置,简化了项目的搭建和开发。将 Spring SecuritySpring Boot 结合使用,可以很方便地实现安全认证和授权功能。 下面是 Spring Boot 整合 Spring Security 的步骤: 1. 在 pom.xml 文件中添加 Spring Security 依赖: ``` <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> ``` 2. 创建一个 Security 配置类,用于配置 Spring Security 的相关参数,如安全拦截规则、用户认证方式等。可以继承 WebSecurityConfigurerAdapter 类,重写 configure 方法来实现配置。 ``` @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/admin/**").hasRole("ADMIN") .antMatchers("/user/**").hasRole("USER") .anyRequest().authenticated() .and() .formLogin() .and() .httpBasic(); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication() .withUser("admin").password("{noop}admin123").roles("ADMIN") .and() .withUser("user").password("{noop}user123").roles("USER"); } } ``` 3. 在配置类中配置用户认证方式。可以使用内存认证、数据库认证或者 LDAP 认证等方式进行用户认证。 4. 配置安全拦截规则。可以通过 antMatchers 方法来设置 URL 的安全拦截规则,如 /admin/** 需要 ADMIN 角色才能访问,/user/** 需要 USER 角色才能访问。 5. 配置登录页面。可以通过 formLogin 方法来配置登录页面的 URL,如 /login。用户输入正确的用户名和密码后,会跳转到登录成功页面。 6. 配置 HTTP Basic 认证。可以通过 httpBasic 方法来开启 HTTP Basic 认证,这样客户端可以使用用户名和密码来访问受保护的资源。 通过上述步骤,就可以将 Spring Security 集成到 Spring Boot 应用程序中,实现安全认证和授权功能。
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值