提交 c9bf52f3 编写于 作者: 马增群

OAuth2.0数据库认证

上级 687ddd47
......@@ -48,6 +48,13 @@
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!-- SpringBoot data JPA -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!--Springboot Security-->
<!--<dependency>
<groupId>org.springframework.boot</groupId>
......@@ -82,22 +89,26 @@
<artifactId>jjwt</artifactId>
<version>${jjwt.version}</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.10</version>
</dependency>
<!-- fatsjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.7</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
......
package org.muses.jeeplatform.oauth.component;
import org.springframework.security.crypto.password.PasswordEncoder;
/**
* <pre>
* 自定义PasswordEncoder
* </pre>
*
* <pre>
* @author mazq
* 修改记录
* 修改后版本: 修改人: 修改日期: 2020/04/24 17:02 修改内容:
* </pre>
*/
public class CustomPasswordEncoder implements PasswordEncoder {
@Override
public String encode(CharSequence charSequence) {
return charSequence.toString();
}
@Override
public boolean matches(CharSequence charSequence, String s) {
String encodeStr = charSequence.toString() + "";
if (encodeStr.equals(s)) {
return true;
}
return false;
}
}
......@@ -103,11 +103,11 @@ public class OAuth2Configuration extends AuthorizationServerConfigurerAdapter {
endpoints.tokenStore(jwtTokenStore()).authenticationManager(authenticationManager)
.accessTokenConverter(accessTokenConverter())
//必须注入userDetailsService否则根据refresh_token无法加载用户信息
//.userDetailsService(userDetailsService)
.userDetailsService(userDetailsService)
//支持获取token方式
.allowedTokenEndpointRequestMethods(HttpMethod.GET, HttpMethod.POST,HttpMethod.PUT,HttpMethod.DELETE,HttpMethod.OPTIONS);
//刷新token
//.reuseRefreshTokens(false)
//.reuseRefreshTokens(true)
//endpoints .tokenServices(tokenServices());
// 使用内存保存生成的token
//endpoints.authenticationManager(authenticationManager).tokenStore(memoryTokenStore());
......@@ -137,11 +137,11 @@ public class OAuth2Configuration extends AuthorizationServerConfigurerAdapter {
@Override
public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
String grantType = authentication.getOAuth2Request().getGrantType();
//只有如下两种模式才能获取到当前用户信息
//授权码和密码模式才自定义token信息
if(AUTHORIZATION_CODE.equals(grantType) || GRANT_TYPE_PASSWORD.equals(grantType)) {
String userName = authentication.getUserAuthentication().getName();
// 自定义一些token 信息 会在获取token返回结果中展示出来
Map<String, Object> additionalInformation = new HashMap<String, Object>();
// 自定义一些token 信息
Map<String, Object> additionalInformation = new HashMap<String, Object>(16);
additionalInformation.put("user_name", userName);
additionalInformation = Collections.unmodifiableMap(additionalInformation);
((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInformation);
......@@ -172,7 +172,7 @@ public class OAuth2Configuration extends AuthorizationServerConfigurerAdapter {
final DefaultTokenServices defaultTokenServices = new DefaultTokenServices();
defaultTokenServices.setTokenEnhancer(accessTokenConverter());
defaultTokenServices.setTokenStore(jwtTokenStore());
defaultTokenServices.setSupportRefreshToken(false);
defaultTokenServices.setSupportRefreshToken(true);
defaultTokenServices.setAccessTokenValiditySeconds((int) TimeUnit.DAYS.toSeconds(30));
return defaultTokenServices;
}
......
package org.muses.jeeplatform.oauth.configuration;
import org.muses.jeeplatform.oauth.component.CustomPasswordEncoder;
import org.muses.jeeplatform.oauth.filter.SimpleCORSFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
......@@ -57,13 +58,14 @@ public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception { //auth.inMemoryAuthentication()
auth.inMemoryAuthentication()
.withUser("nicky")
.password("{noop}123")
.roles("admin");
// auth.userDetailsService(userDetailsService)
// .passwordEncoder(bCryptPasswordEncoder());
// auth.parentAuthenticationManager(authenticationManagerBean());
// auth.inMemoryAuthentication()
// .withUser("nicky")
// .password("{noop}123")
// .roles("admin");
auth.userDetailsService(userDetailsService)
.passwordEncoder(new CustomPasswordEncoder());
auth.parentAuthenticationManager(authenticationManagerBean());
}
@Override
......
package org.muses.jeeplatform.core.entity.admin;
import com.alibaba.fastjson.annotation.JSONField;
import javax.persistence.*;
import java.io.Serializable;
import java.util.Date;
import java.util.Set;
/**
* 用户信息的实体类
* @author Nicky
*/
@Entity
@Table(name="sys_user")
public class User implements Serializable{
/** 用户Id**/
private int id;
/** 用户名**/
private String username;
/** 用户密码**/
private String password;
/** 手机号**/
private String phone;
/** 性别**/
private String sex;
/** 邮件**/
private String email;
/** 备注**/
private String mark;
/** 用户级别**/
private String rank;
/** 最后一次时间**/
private Date lastLogin;
/** 登录ip**/
private String loginIp;
/** 图片路径**/
private String imageUrl;
/** 注册时间**/
private Date regTime;
/** 账号是否被锁定**/
private Boolean locked = Boolean.FALSE;
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Id
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Column(unique=true,length=100,nullable=false)
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
@Column(length=100,nullable=false)
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Column(length = 11)
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
@Column(length=6)
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
@Column(length=100)
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Column(length=100)
public String getMark() {
return mark;
}
public void setMark(String mark) {
this.mark = mark;
}
@Column(length=10)
public String getRank() {
return rank;
}
public void setRank(String rank) {
this.rank = rank;
}
@Temporal(TemporalType.DATE)
@JSONField(format ="yyyy-MM-dd HH:mm:ss")
public Date getLastLogin() {
return lastLogin;
}
public void setLastLogin(Date lastLogin) {
this.lastLogin = lastLogin;
}
@Column(length=100)
public String getLoginIp() {
return loginIp;
}
public void setLoginIp(String loginIp) {
this.loginIp = loginIp;
}
@Column(length=100)
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
@Temporal(TemporalType.DATE)
@Column(nullable=false)
@JSONField(format ="yyyy-MM-dd HH:mm:ss")
public Date getRegTime() {
return regTime;
}
public void setRegTime(Date regTime) {
this.regTime = regTime;
}
public Boolean getLocked() {
return locked;
}
public void setLocked(Boolean locked) {
this.locked = locked;
}
}
package org.muses.jeeplatform.oauth.dto;
package org.muses.jeeplatform.oauth.entity.dto;
import lombok.AllArgsConstructor;
import lombok.Data;
......@@ -9,7 +9,7 @@ import java.util.Date;
/**
* <pre>
*
* 用户信息DTO类
* </pre>
*
* <pre>
......
package org.muses.jeeplatform.oauth.repository;
import org.muses.jeeplatform.oauth.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
/**
* <pre>
*
* </pre>
*
* <pre>
* @author mazq
* 修改记录
* 修改后版本: 修改人: 修改日期: 2020/05/15 17:34 修改内容:
* </pre>
*/
public interface UserRepository extends JpaRepository<User,Integer> {
User findByUsername(String username);
@Query(value = "select u from User u where u.username=:username and u.password=:password")
User findByUsernameAndPassword(@Param("username") String username, @Param("password") String password);
}
package org.muses.jeeplatform.oauth.service;
import lombok.extern.slf4j.Slf4j;
import org.muses.jeeplatform.oauth.dto.UserDto;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.muses.jeeplatform.oauth.entity.User;
import org.muses.jeeplatform.oauth.entity.dto.UserDto;
import org.muses.jeeplatform.oauth.repository.UserRepository;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
......@@ -27,18 +30,23 @@ import java.util.List;
@Service("userService")
public class UserDetailsServiceImpl implements UserDetailsService {
@Autowired
UserRepository userRepository;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
UserDto user = new UserDto();
// if(user == null){
// log.info("登录用户[{}]没注册!",username);
// throw new UsernameNotFoundException("登录用户["+username + "]没注册!");
// }
return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), getAuthority());
User user = userRepository.findByUsername(username);
UserDto userDto = new UserDto();
BeanUtils.copyProperties(user,userDto);
if(userDto == null){
log.info("登录用户[{}]没注册!",username);
throw new UsernameNotFoundException("登录用户["+username + "]没注册!");
}
return new org.springframework.security.core.userdetails.User(userDto.getUsername(), userDto.getPassword(), getAuthority());
}
private List getAuthority() {
//return Arrays.asList(new SimpleGrantedAuthority("admin"));
//return Arrays.asList(new SimpleGrantedAuthority("ROLE_ADMIN"));
return Arrays.asList(Collections.emptyList());
}
}
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册