SpringBoot 2.x 集成SpringSecurity(一)之用户认证

一、快速入门

1、pom文件引用SpringSecurity、Lombok依赖,其中Lombok方便快速开发,具体使用方法自行google

<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <optional>true</optional>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>

2、创建controller,com.jefry.security.controller.HelloController

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@RestController
public class hello {

    @GetMapping("/demo")
    public String demo() {
        return "Demo";
    }
}

3、运行项目,使用浏览器访问127.0.0.1:8080/demo,提示需要输入账号密码;

在这里插入图片描述

账号:user,密码在运行日志里可以看到,每次运行都会变化:

Using generated security password: 66b0dd4f-d61f-46ac-b644-d389a55629ea

输入账号密码,登录成功:
在这里插入图片描述

若运行没有提示登录,检查下spring security依赖是否已经导入成功,IDEA可以在pom.xml文件右击->maven->reimport。

4、默认会开启http base认证与from表单认证,我们修改为http base可以这么做。

新建com.jefry.security.config包,在此包下新增WebSecurityConfig继承WebSecurityConfigurerAdapter,代码如下:

package com.jefry.security.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
                .httpBasic()
                .and()
                .authorizeRequests()
                .anyRequest()
                .authenticated();
    }
}

5、运行后会提示需要http base认证。
在这里插入图片描述

二、修改登录验证界面:

1、新增login.html文件,放在resources/static目录下面,代码如下:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>登录</title>
</head>
<body>
<form class="login-page" action="/login" method="post">
    <div class="form">
        <h3>账户登录</h3>
        <input type="text" placeholder="用户名" name="username" required="required" />
        <input type="password" placeholder="密码" name="password" required="required" />
        <button type="submit">登录</button>
    </div>
</form>
</body>
</html>

2、修改WebSecurityConfig文件,代码如下:

package com.jefry.security.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
                .formLogin()
                .loginPage("/login.html") //登录界面
                .loginProcessingUrl("/login") //登录认证地址,需与from表的action保持一致
                .and()
                .authorizeRequests()
                .antMatchers("/login.html").permitAll() //不需登录可以访问的地址
                .anyRequest()
                .authenticated();
    }
}

3、再次访问http://127.0.0.1:8080/demo,会跳转到http://127.0.0.1:8080/login.html,正是配置的.loginPage("/login.html") ,此时界面变成修改后的了。

在这里插入图片描述

4、输入账号密码,账号密码还是上面的获取方式,会自动跳转到http://127.0.0.1:8080/demo。

在这里插入图片描述

三、修改验证密码:

1、新增com.jefry.security.service包,并新增UserDetailService类,代码如下:

package com.jefry.security.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class UserDetailService implements UserDetailsService {
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        log.info("登录账号:{}",username);
        return new User(username, "123456", AuthorityUtils.commaSeparatedStringToAuthorityList("admin"));
    }
}

2、重新运行,访问http://127.0.0.1:8080 输入账号密码,看控制台有如下输出:

java.lang.IllegalArgumentException: There is no PasswordEncoder mapped for the id "null"

提示大意就是密码未进行编码。

3、增加密码编码,在WebSecurityConfig 修改如下:

package com.jefry.security.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
                .formLogin()
                .loginPage("/login.html") //登录界面
                .loginProcessingUrl("/login") //登录认证地址
                .and()
                .authorizeRequests()
                .antMatchers("/login.html").permitAll() //不需登录可以访问的地址
                .anyRequest()
                .authenticated();
    }

    /**
     * 增加密码加密
     * @return
     */
    @Bean
    PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }
}

4、UserDetailService增加PasswordEncoder注入,代码修改如下:

package com.jefry.security.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class UserDetailService implements UserDetailsService {

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        log.info("登录账号:{}", username);
        String password = passwordEncoder.encode("123456");
        return new User(username, password, AuthorityUtils.commaSeparatedStringToAuthorityList("admin"));
    }
}

5、重新访问http://127.0.0.1:8080/demo,输入账号密码,账号随意,密码:123456。

控制台输出类似日志:

登录账号:user,密码:$2a$10$XQZL77eSp0KAfb8FAN96VeBDQtJCHLEVnXaQ.EbE8w0ZPjpBTwqaa

四、自定义登录成功与失败返回

1、新增com.jefry.security.handler包,创建继承AuthenticationSuccessHandler的AuthenticationSuccessHandlerImpl类;代码如下:

package com.jefry.security.handler.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
@Slf4j
public class AuthenticationSuccessHandlerImpl implements AuthenticationSuccessHandler {
    @Autowired
    public ObjectMapper objectMapper;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        log.info("登录成功");
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(objectMapper.writeValueAsString(authentication));
    }
}

2、在同目录下创建继承AuthenticationFailureHandler的AuthenticationFailureHandlerImpl类,代码如下:
package com.jefry.security.handler.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
@Slf4j
public class AuthenticationFailureHandlerImpl implements AuthenticationFailureHandler {
    @Autowired
    ObjectMapper objectMapper;

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        log.info("登录失败");
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(objectMapper.writeValueAsString(exception));
    }
}

3、修改WebSecurityConfig类,代码如下:

package com.jefry.security.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    AuthenticationSuccessHandler authenticationSuccessHandler;

    @Autowired
    AuthenticationFailureHandler authenticationFailureHandler;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
                .formLogin()
                .loginPage("/login.html") //登录界面
                .loginProcessingUrl("/login") //登录认证地址
                .successHandler(authenticationSuccessHandler)
                .failureHandler(authenticationFailureHandler)
                .and()
                .authorizeRequests()
                .antMatchers("/login.html").permitAll() //不需登录可以访问的地址
                .anyRequest()
                .authenticated();
    }

    /**
     * 增加密码加密
     * @return
     */
    @Bean
    PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }
}

4、访问http://127.0.0.1/demo,分别输入正确的密码与错误的密码查看浏览器的提示信息。

五、跟从DB中判断账号与密码

1、在mysql 的库中新建user表,包含三个字段,id,username,password。

2、使用mybatis访问mysql,mybatis使用方式自动查找,JPA也可以。

3、新增UserEntity类,代码如下:

package com.jefry.security.entity;

import lombok.Data;
import org.springframework.stereotype.Service;

@Service
@Data
public class UserEntity {
    private int id;
    private String username;
    private String password;
}

4、新增UserService类,代码如下:

package com.jefry.security.service;

import com.jefry.security.entity.UserEntity;
import com.jefry.security.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserService {
    @Autowired
    UserMapper userMapper;

    public UserEntity loadUsername(String username) {
        return userMapper.loadByUsername(username);
    }
}

5、修改UserDetailService类,代码如下:

package com.jefry.security.service;

import com.jefry.security.entity.UserEntity;
import com.jefry.security.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
@Slf4j
public class UserDetailService implements UserDetailsService {

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserEntity userEntity = userService.loadUsername(username);
        if (userEntity == null) {
            throw new UsernameNotFoundException("账号不存在");
        }
        String password = passwordEncoder.encode(userEntity.getPassword());
        log.info("登录账号:{},密码:{}", username, password);
        return new User(username, password, AuthorityUtils.commaSeparatedStringToAuthorityList("admin"));
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值