提交 6d32c460 authored 作者: Whispa's avatar Whispa

third commit

上级 cf3c9bd4
...@@ -27,6 +27,22 @@ ...@@ -27,6 +27,22 @@
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId> <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency> </dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.security.oauth/spring-security-oauth2 -->
<dependency>
<groupId>org.springframework.security.oauth</groupId>
<artifactId>spring-security-oauth2</artifactId>
<version>2.1.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version>
</dependency>
<dependency> <dependency>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-client</artifactId> <artifactId>spring-boot-starter-oauth2-client</artifactId>
......
package com.example.afrishop_v3.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/").permitAll();
http.csrf().disable().authorizeRequests().anyRequest().permitAll();
}
}
package com.example.afrishop_v3.controllers;
import com.example.afrishop_v3.base.Result;
import com.example.afrishop_v3.enums.ResultCodeEnum;
import com.example.afrishop_v3.models.TbCfUserInfo;
import com.example.afrishop_v3.payload.request.LoginRequest;
import com.example.afrishop_v3.payload.response.JwtResponse;
import com.example.afrishop_v3.payload.response.MessageResponse;
import com.example.afrishop_v3.repository.UserRepository;
import com.example.afrishop_v3.security.jwt.JwtUtils;
import com.example.afrishop_v3.security.services.UserDetailsImpl;
import com.example.afrishop_v3.util.IdUtil;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
@CrossOrigin(origins = "*", maxAge = 3600)
@RestController
@RequestMapping("/api/auth")
public class AuthController {
private final AuthenticationManager authenticationManager;
private final UserRepository userRepository;
private final PasswordEncoder encoder;
private final JwtUtils jwtUtils;
public AuthController(AuthenticationManager authenticationManager, UserRepository userRepository, PasswordEncoder encoder, JwtUtils jwtUtils) {
this.authenticationManager = authenticationManager;
this.userRepository = userRepository;
this.encoder = encoder;
this.jwtUtils = jwtUtils;
}
@PostMapping("/signin")
public ResponseEntity<Result> authenticateUser(@RequestBody LoginRequest loginRequest) {
Optional<TbCfUserInfo> byAccount = userRepository.findByAccount(loginRequest.getAccount());
if( !byAccount.isPresent() ){
return ResponseEntity.ok(new Result<>(ResultCodeEnum.VALIDATE_ERROR,"User not found"));
}
Authentication authentication = authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(loginRequest.getAccount(), loginRequest.getPassword()));
SecurityContextHolder.getContext().setAuthentication(authentication);
String jwt = jwtUtils.generateJwtToken(authentication);
UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal();
List<String> roles = userDetails.getAuthorities().stream()
.map(GrantedAuthority::getAuthority)
.collect(Collectors.toList());
return ResponseEntity.ok(new Result<>(new JwtResponse(jwt,
userDetails.getId(),
userDetails.getUsername(),
userDetails.getEmail(),
roles)));
}
@PostMapping("/signup")
public ResponseEntity<?> registerUser( @RequestBody TbCfUserInfo signUpRequest) {
Optional<TbCfUserInfo> byAccount = userRepository.findByAccount(signUpRequest.getAccount());
if ( byAccount.isPresent() ) {
return ResponseEntity
.badRequest()
.body(new MessageResponse("Error: Username is already taken!"));
}
Optional<TbCfUserInfo> byEmail = userRepository.findFirstByEmail(signUpRequest.getEmail());
if ( byEmail.isPresent() ) {
return ResponseEntity
.badRequest()
.body(new MessageResponse("Error: Email is already in use!"));
}
signUpRequest.setUserId(IdUtil.createIdbyUUID());
signUpRequest.setPassword(encoder.encode(signUpRequest.getPassword()));
TbCfUserInfo userInfo = userRepository.save(signUpRequest);
return ResponseEntity.ok(new Result<>(userInfo,"User createdSuccessfully"));
}
}
package com.example.afrishop_v3.controllers;
import com.example.afrishop_v3.base.Result;
import com.example.afrishop_v3.models.TbCfFeedback;
import com.example.afrishop_v3.repository.TbCfFeedbackRepository;
import com.example.afrishop_v3.security.services.AuthenticationUser;
import com.example.afrishop_v3.util.IdUtil;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/feedback")
public class FeedbackController {
private final TbCfFeedbackRepository repository;
public FeedbackController(TbCfFeedbackRepository repository) {
this.repository = repository;
}
@PostMapping
public Result saveFeedbackList(@RequestBody TbCfFeedback feedback) {
feedback.setFeedbackId(IdUtil.createIdbyUUID());
return new Result<>(repository.save(feedback));
}
@GetMapping
public Result getFeedbackList() {
return new Result<>(repository.findAll());
}
}
...@@ -5,12 +5,14 @@ import com.example.afrishop_v3.enums.ResultCodeEnum; ...@@ -5,12 +5,14 @@ import com.example.afrishop_v3.enums.ResultCodeEnum;
import com.example.afrishop_v3.models.TbCfSearch; import com.example.afrishop_v3.models.TbCfSearch;
import com.example.afrishop_v3.repository.TbCfSearchRepository; import com.example.afrishop_v3.repository.TbCfSearchRepository;
import com.example.afrishop_v3.util.IdUtil; import com.example.afrishop_v3.util.IdUtil;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import java.util.List; import java.util.List;
@RestController @RestController
@RequestMapping("/search") @RequestMapping("/search")
@PreAuthorize("hasRole('user')")
public class SearchController { public class SearchController {
private final TbCfSearchRepository repository; private final TbCfSearchRepository repository;
......
package com.example.afrishop_v3.models;
import lombok.Getter;
import lombok.Setter;
import javax.persistence.Entity;
import javax.persistence.Id;
import java.util.Date;
/**
* 反馈问题列表实体
* 表名 tb_cf_feedback
*
* @author lipengjun
* @date 2019-09-21 15:15:23
*/
@Entity
@Getter
@Setter
public class TbCfFeedback{
/**
* 反馈问题id
*/
@Id
private String feedbackId;
/**
* 问题
*/
private String question;
/**
* 是否展示,1展示,0不展示
*/
private Integer enableFlag;
/**
* 创建时间
*/
private Date createTime;
/**
* 反馈问题类型,1为填写类型
*/
private Integer questionType;
/**
* 排序,数字,倒序
*/
private Integer sort;
/**
* 设置:反馈问题id
*/
public void setFeedbackId(String feedbackId) {
this.feedbackId = feedbackId;
}
/**
* 获取:反馈问题id
*/
public String getFeedbackId() {
return feedbackId;
}
/**
* 设置:问题
*/
public void setQuestion(String question) {
this.question = question;
}
/**
* 获取:问题
*/
public String getQuestion() {
return question;
}
/**
* 设置:是否展示,1展示,0不展示
*/
public void setEnableFlag(Integer enableFlag) {
this.enableFlag = enableFlag;
}
/**
* 获取:是否展示,1展示,0不展示
*/
public Integer getEnableFlag() {
return enableFlag;
}
/**
* 设置:创建时间
*/
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
/**
* 获取:创建时间
*/
public Date getCreateTime() {
return createTime;
}
/**
* 设置:反馈问题类型,1为填写类型
*/
public void setQuestionType(Integer questionType) {
this.questionType = questionType;
}
/**
* 获取:反馈问题类型,1为填写类型
*/
public Integer getQuestionType() {
return questionType;
}
/**
* 设置:排序,数字,倒序
*/
public void setSort(Integer sort) {
this.sort = sort;
}
/**
* 获取:排序,数字,倒序
*/
public Integer getSort() {
return sort;
}
}
package com.example.afrishop_v3.models;
import lombok.Getter;
import lombok.Setter;
import javax.persistence.Entity;
import javax.persistence.Id;
import java.util.Date;
/**
* 用户反馈记录表实体
* 表名 tb_cf_feedback_record
*
* @author lipengjun
* @date 2019-09-21 15:15:23
*/
@Entity
@Getter
@Setter
public class TbCfFeedbackRecord {
/**
* 反馈记录id
*/
@Id
private String recordId;
/**
* 反馈用户id
*/
private String userId;
/**
* 反馈问题id
*/
private String feedbackId;
/**
* 反馈填写内容
*/
private String answer;
/**
* 创建时间
*/
private Date createTime;
/**
* 设置:反馈记录id
*/
public void setRecordId(String recordId) {
this.recordId = recordId;
}
/**
* 获取:反馈记录id
*/
public String getRecordId() {
return recordId;
}
/**
* 设置:反馈用户id
*/
public void setUserId(String userId) {
this.userId = userId;
}
/**
* 获取:反馈用户id
*/
public String getUserId() {
return userId;
}
/**
* 设置:反馈问题id
*/
public void setFeedbackId(String feedbackId) {
this.feedbackId = feedbackId;
}
/**
* 获取:反馈问题id
*/
public String getFeedbackId() {
return feedbackId;
}
/**
* 设置:反馈填写内容
*/
public void setAnswer(String answer) {
this.answer = answer;
}
/**
* 获取:反馈填写内容
*/
public String getAnswer() {
return answer;
}
/**
* 设置:创建时间
*/
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
/**
* 获取:创建时间
*/
public Date getCreateTime() {
return createTime;
}
}
...@@ -6,6 +6,8 @@ import lombok.Setter; ...@@ -6,6 +6,8 @@ import lombok.Setter;
import javax.persistence.Entity; import javax.persistence.Entity;
import javax.persistence.Id; import javax.persistence.Id;
import java.io.Serializable; import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date; import java.util.Date;
/** /**
...@@ -428,4 +430,10 @@ public class TbCfUserInfo { ...@@ -428,4 +430,10 @@ public class TbCfUserInfo {
public Integer getIsSend() { public Integer getIsSend() {
return isSend; return isSend;
} }
public Collection<String> getRoles() {
ArrayList<String> objects = new ArrayList<>();
objects.add("user");
return objects;
}
} }
package com.example.afrishop_v3.payload.request;
public class LoginRequest {
private String account;
private String password;
public String getAccount() {
return account;
}
public void setAccount(String account) {
this.account = account;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
package com.example.afrishop_v3.payload.response;
import java.util.List;
public class JwtResponse {
private String token;
private String type = "Bearer";
private String id;
private String username;
private String email;
private List<String> roles;
public JwtResponse(String accessToken, String id, String username, String email, List<String> roles) {
this.token = accessToken;
this.id = id;
this.username = username;
this.email = email;
this.roles = roles;
}
public String getAccessToken() {
return token;
}
public void setAccessToken(String accessToken) {
this.token = accessToken;
}
public String getTokenType() {
return type;
}
public void setTokenType(String tokenType) {
this.type = tokenType;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public List<String> getRoles() {
return roles;
}
}
package com.example.afrishop_v3.payload.response;
public class MessageResponse {
private String message;
public MessageResponse(String message) {
this.message = message;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
package com.example.afrishop_v3.repository;
import com.example.afrishop_v3.models.TbCfFeedbackRecord;
import org.springframework.data.repository.PagingAndSortingRepository;
public interface TbCfFeedbackRecordRepository extends PagingAndSortingRepository<TbCfFeedbackRecord,String> {
}
package com.example.afrishop_v3.repository;
import com.example.afrishop_v3.models.TbCfFeedback;
import org.springframework.data.repository.PagingAndSortingRepository;
public interface TbCfFeedbackRepository extends PagingAndSortingRepository<TbCfFeedback,String> {
}
package com.example.afrishop_v3.repository;
import com.example.afrishop_v3.models.TbCfUserInfo;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.Optional;
public interface UserRepository extends PagingAndSortingRepository<TbCfUserInfo,String> {
Optional<TbCfUserInfo> findByAccount(String s);
Optional<TbCfUserInfo> findFirstByEmail(String s);
}
package com.example.afrishop_v3.security;
import com.example.afrishop_v3.security.jwt.AuthEntryPointJwt;
import com.example.afrishop_v3.security.jwt.AuthTokenFilter;
import com.example.afrishop_v3.security.services.UserDetailsServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(
// securedEnabled = true,
// jsr250Enabled = true,
prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
UserDetailsServiceImpl userDetailsService;
@Autowired
private AuthEntryPointJwt unauthorizedHandler;
@Bean
public AuthTokenFilter authenticationJwtTokenFilter() {
return new AuthTokenFilter();
}
@Override
public void configure(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception {
authenticationManagerBuilder.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
}
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors().and().csrf().disable()
.exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
.authorizeRequests().antMatchers("/api/auth/**").permitAll()
.antMatchers("/api/test/**").permitAll()
.anyRequest().authenticated();
http.addFilterBefore(authenticationJwtTokenFilter(), UsernamePasswordAuthenticationFilter.class);
}
}
package com.example.afrishop_v3.security.jwt;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;
@Component
public class AuthEntryPointJwt implements AuthenticationEntryPoint {
private static final Logger logger = LoggerFactory.getLogger(AuthEntryPointJwt.class);
@Override
public void commence(HttpServletRequest request, HttpServletResponse response,
AuthenticationException authException) throws IOException, ServletException {
logger.error("Unauthorized error: {}", authException.getMessage());
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Error: Unauthorized");
}
}
package com.example.afrishop_v3.security.jwt;
import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.example.afrishop_v3.security.services.UserDetailsServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;
public class AuthTokenFilter extends OncePerRequestFilter {
@Autowired
private JwtUtils jwtUtils;
@Autowired
private UserDetailsServiceImpl userDetailsService;
private static final Logger logger = LoggerFactory.getLogger(AuthTokenFilter.class);
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
try {
String jwt = parseJwt(request);
if (jwt != null && jwtUtils.validateJwtToken(jwt)) {
String username = jwtUtils.getUserNameFromJwtToken(jwt);
UserDetails userDetails = userDetailsService.loadUserByUsername(username);
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
userDetails, null, userDetails.getAuthorities());
authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
SecurityContextHolder.getContext().setAuthentication(authentication);
}
} catch (Exception e) {
logger.error("Cannot set user authentication: {}", e);
}
filterChain.doFilter(request, response);
}
private String parseJwt(HttpServletRequest request) {
String headerAuth = request.getHeader("Authorization");
if (StringUtils.hasText(headerAuth) && headerAuth.startsWith("Bearer ")) {
return headerAuth.substring(7, headerAuth.length());
}
return null;
}
}
package com.example.afrishop_v3.security.jwt;
import java.util.Date;
import com.example.afrishop_v3.security.services.UserDetailsImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;
import io.jsonwebtoken.*;
@Component
public class JwtUtils {
private static final Logger logger = LoggerFactory.getLogger(JwtUtils.class);
@Value("${bezkoder.app.jwtSecret}")
private String jwtSecret;
@Value("${bezkoder.app.jwtExpirationMs}")
private int jwtExpirationMs;
public String generateJwtToken(Authentication authentication) {
UserDetailsImpl userPrincipal = (UserDetailsImpl) authentication.getPrincipal();
return Jwts.builder()
.setSubject((userPrincipal.getUsername()))
.setIssuedAt(new Date())
.setExpiration(new Date((new Date()).getTime() + jwtExpirationMs))
.signWith(SignatureAlgorithm.HS512, jwtSecret)
.compact();
}
public String getUserNameFromJwtToken(String token) {
return Jwts.parser().setSigningKey(jwtSecret).parseClaimsJws(token).getBody().getSubject();
}
public boolean validateJwtToken(String authToken) {
try {
Jwts.parser().setSigningKey(jwtSecret).parseClaimsJws(authToken);
return true;
} catch (SignatureException e) {
logger.error("Invalid JWT signature: {}", e.getMessage());
} catch (MalformedJwtException e) {
logger.error("Invalid JWT token: {}", e.getMessage());
} catch (ExpiredJwtException e) {
logger.error("JWT token is expired: {}", e.getMessage());
} catch (UnsupportedJwtException e) {
logger.error("JWT token is unsupported: {}", e.getMessage());
} catch (IllegalArgumentException e) {
logger.error("JWT claims string is empty: {}", e.getMessage());
}
return false;
}
}
package com.example.afrishop_v3.security.services;
import com.example.afrishop_v3.models.TbCfUserInfo;
import com.example.afrishop_v3.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
@Component
public class AuthenticationUser implements IAuthenticationFacade {
private final UserRepository repository;
public AuthenticationUser(UserRepository repository) {
this.repository = repository;
}
@Override
public Authentication getAuthentication() {
return SecurityContextHolder.getContext().getAuthentication();
}
public TbCfUserInfo userInfo(){
return repository.findByAccount(getAuthentication().getName()).orElseGet(null);
}
}
package com.example.afrishop_v3.security.services;
import org.springframework.security.core.Authentication;
interface IAuthenticationFacade {
Authentication getAuthentication();
}
package com.example.afrishop_v3.security.services;
import java.util.Collection;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import com.example.afrishop_v3.models.TbCfUserInfo;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import com.fasterxml.jackson.annotation.JsonIgnore;
public class UserDetailsImpl implements UserDetails {
private static final long serialVersionUID = 1L;
private String id;
private String username;
private String email;
@JsonIgnore
private String password;
private Collection<? extends GrantedAuthority> authorities;
public UserDetailsImpl(String id, String username, String email, String password,
Collection<? extends GrantedAuthority> authorities) {
this.id = id;
this.username = username;
this.email = email;
this.password = password;
this.authorities = authorities;
}
public static UserDetailsImpl build(TbCfUserInfo user) {
List<GrantedAuthority> authorities = user.getRoles().stream()
.map(SimpleGrantedAuthority::new)
.collect(Collectors.toList());
return new UserDetailsImpl(
user.getUserId(),
user.getAccount(),
user.getEmail(),
user.getPassword(),
authorities);
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return authorities;
}
public String getId() {
return id;
}
public String getEmail() {
return email;
}
@Override
public String getPassword() {
return password;
}
@Override
public String getUsername() {
return username;
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return true;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
UserDetailsImpl user = (UserDetailsImpl) o;
return Objects.equals(id, user.id);
}
}
package com.example.afrishop_v3.security.services;
import com.example.afrishop_v3.models.TbCfUserInfo;
import com.example.afrishop_v3.repository.UserRepository;
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;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
private final UserRepository userRepository;
public UserDetailsServiceImpl(UserRepository userRepository) {
this.userRepository = userRepository;
}
@Override
@Transactional
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
TbCfUserInfo user = userRepository.findByAccount(username)
.orElseThrow(() -> new UsernameNotFoundException("User Not Found with username: " + username));
return UserDetailsImpl.build(user);
}
}
...@@ -13,8 +13,12 @@ security.jwt.client-id=whispajwtclientid ...@@ -13,8 +13,12 @@ security.jwt.client-id=whispajwtclientid
security.jwt.client-secret=XY7kmzoNzl100 security.jwt.client-secret=XY7kmzoNzl100
security.jwt.grant-type=password security.jwt.grant-type=password
security.jwt.scope-read=read security.jwt.scope-read=read
jwt.secret=javainuse
security.jwt.scope-write=write security.jwt.scope-write=write
security.jwt.resource-ids=testjwtresourceid security.jwt.resource-ids=testjwtresourceid
spring.servlet.multipart.max-file-size=456128KB spring.servlet.multipart.max-file-size=456128KB
spring.servlet.multipart.max-request-size=456128KB spring.servlet.multipart.max-request-size=456128KB
# App Properties
bezkoder.app.jwtSecret= bezKoderSecretKey
bezkoder.app.jwtExpirationMs= 86400000
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论