springboot整合security(二)

今天说说连接数据库实现security登录

首先还是建一个springboot项目

包结构如下

securityConfig

package com.example.security02.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Configuration;
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.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

import java.util.HashMap;
import java.util.Map;

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        super.configure(auth);
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        super.configure(web);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable();
        http.formLogin().usernameParameter("user")//设置用户参数名,默认为username
                .passwordParameter("pass")//设置用户密码参数名,默认为password
//                .loginPage("/login.html")//设置登录页面
                .loginProcessingUrl("/login")//设置登录接口api
                .successHandler((req,resp,auth)->{//成功处理器
                    Map<String, Object> hashMap = new HashMap<>();
                    hashMap.put("status", "200");//成功返回200
                    hashMap.put("message","ok");
                    hashMap.put("data","");
                    ObjectMapper mapper=new ObjectMapper();
                    mapper.writeValue(resp.getWriter(),hashMap);
                })
                .failureHandler((req,resp,auth)->{//失败处理器
                    Map<String, Object> hashMap = new HashMap<>();
                    hashMap.put("status", "500");//失败返回500
                    hashMap.put("message","no");
                    hashMap.put("data","");
                    ObjectMapper mapper=new ObjectMapper();
                    mapper.writeValue(resp.getWriter(),hashMap);
                })
                .permitAll();

        http.authorizeRequests().anyRequest().authenticated();
    }
}

数据库测试sql,密码是加密后的123

CREATE TABLE `users`  (
  `uid` int(11) NOT NULL AUTO_INCREMENT,
  `uname` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL,
  `pword` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL,
  PRIMARY KEY (`uid`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 5 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic;


INSERT INTO `users` VALUES (1, '张三', '$2a$10$G7VMMVhrT8GsxkODhuOc5OBs1aqWIGQ1jBrQEpSXIMo0L500PSloG');

Users

package com.example.security02.entity;

import lombok.Data;

@Data
public class Users {
    private Integer uid;
    private String uname;
    private String pword;
}

UsersMapper

package com.example.security02.mapper;

import com.example.security02.entity.Users;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;

@Mapper
public interface UsersMapper {
    @Select("select * from users where uname=#{uname}")
    Users query(String uname);
}
MyUserDetailService
package com.example.security02.modal;

import com.example.security02.entity.Users;
import com.example.security02.service.UsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
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;

import java.util.List;

@Component
public class MyUserDetailService implements UserDetailsService {
    @Autowired
    UsersService us;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        Users u=us.query(s);
        List<GrantedAuthority> admin = AuthorityUtils.createAuthorityList("admin");
        return new User(u.getUname(),u.getPword(),admin);
    }
}

security,这是密码加密和比较的对象

package com.example.security02.modal;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
public class security {

    @Bean
    PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }
}

UserService

package com.example.security02.service;

import com.example.security02.entity.Users;

public interface UsersService {
    Users query(String uname);
}

UserServiceImpl

package com.example.security02.service.impl;

import com.example.security02.entity.Users;
import com.example.security02.mapper.UsersMapper;
import com.example.security02.service.UsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UsersServiceImpl implements UsersService {

    @Autowired
    UsersMapper um;

    @Override
    public Users query(String uname) {
        return um.query(uname);
    }
}

配置文件

到此完成,使用postman测试

连接数据库登录到此就成功啦~

明天讲解整合jwt进行token认证~

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

心心丶念念

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

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

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

打赏作者

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

抵扣说明:

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

余额充值