今天说说连接数据库实现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认证~