diff --git a/mall-portal/pom.xml b/mall-portal/pom.xml index 69e53fa..5b637fd 100644 --- a/mall-portal/pom.xml +++ b/mall-portal/pom.xml @@ -30,8 +30,8 @@ mall-mbg - org.springframework.boot - spring-boot-starter-security + com.macro.mall + mall-security diff --git a/mall-portal/src/main/java/com/macro/mall/portal/config/MallSecurityConfig.java b/mall-portal/src/main/java/com/macro/mall/portal/config/MallSecurityConfig.java new file mode 100644 index 0000000..456cc18 --- /dev/null +++ b/mall-portal/src/main/java/com/macro/mall/portal/config/MallSecurityConfig.java @@ -0,0 +1,29 @@ +package com.macro.mall.portal.config; + +import com.macro.mall.portal.service.UmsMemberService; +import com.macro.mall.security.config.SecurityConfig; +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.method.configuration.EnableGlobalMethodSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.core.userdetails.UserDetailsService; + +/** + * mall-security模块相关配置 + * Created by macro on 2019/11/5. + */ +@Configuration +@EnableWebSecurity +@EnableGlobalMethodSecurity(prePostEnabled=true) +public class MallSecurityConfig extends SecurityConfig { + + @Autowired + private UmsMemberService memberService; + + @Bean + public UserDetailsService userDetailsService() { + //获取登录用户信息 + return username -> memberService.loadUserByUsername(username); + } +} diff --git a/mall-portal/src/main/java/com/macro/mall/portal/config/SecurityConfig.java b/mall-portal/src/main/java/com/macro/mall/portal/config/SecurityConfig.java deleted file mode 100644 index ac40ba0..0000000 --- a/mall-portal/src/main/java/com/macro/mall/portal/config/SecurityConfig.java +++ /dev/null @@ -1,111 +0,0 @@ -package com.macro.mall.portal.config; - -import com.macro.mall.model.UmsMember; -import com.macro.mall.portal.component.*; -import com.macro.mall.portal.domain.MemberDetails; -import com.macro.mall.portal.service.UmsMemberService; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.http.HttpMethod; -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.configuration.EnableWebSecurity; -import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; -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.bcrypt.BCryptPasswordEncoder; -import org.springframework.security.crypto.password.PasswordEncoder; - -/** - * SpringSecurity的配置 - * Created by macro on 2018/8/3. - */ -@Configuration -@EnableWebSecurity -public class SecurityConfig extends WebSecurityConfigurerAdapter { - @Autowired - private UmsMemberService memberService; - @Override - protected void configure(HttpSecurity http) throws Exception { - http.authorizeRequests() - .antMatchers(HttpMethod.GET, // 允许对于网站静态资源的无授权访问 - "/", - "/*.html", - "/favicon.ico", - "/**/*.html", - "/**/*.css", - "/**/*.js", - "/swagger-resources/**", - "/v2/api-docs/**", - "/webjars/springfox-swagger-ui/**" - ) - .permitAll() - .antMatchers(HttpMethod.OPTIONS)//跨域请求会先进行一次options请求 - .permitAll() - .antMatchers( - "/sso/*",//登录注册 - "/home/**"//首页接口 - ) - .permitAll() - .antMatchers("/member/**","/returnApply/**")// 测试时开启 - .permitAll() - .anyRequest()// 除上面外的所有请求全部需要鉴权认证 - .authenticated() - .and() - .exceptionHandling() - .accessDeniedHandler(new GoAccessDeniedHandler()) - .authenticationEntryPoint(new GoAuthenticationEntryPoint()) - .and() - .formLogin() - .loginPage("/sso/login") - .successHandler(new GoAuthenticationSuccessHandler()) - .failureHandler(new GoAuthenticationFailureHandler()) - .and() - .logout() - .logoutUrl("/sso/logout") - .logoutSuccessHandler(new GoLogoutSuccessHandler()) - .invalidateHttpSession(true) - .deleteCookies("JSESSIONID") -// .and() -// .requiresChannel() -// .antMatchers("/sso/*") -// .requiresSecure() -// .anyRequest() -// .requiresInsecure() -// .and() -// .rememberMe() -// .tokenValiditySeconds(1800) -// .key("token_key") - .and() - .csrf() - .disable();//开启basic认证登录后可以调用需要认证的接口 - } - - @Override - protected void configure(AuthenticationManagerBuilder auth) throws Exception { - auth.userDetailsService(userDetailsService()) - .passwordEncoder(passwordEncoder()); - } - - @Bean - public PasswordEncoder passwordEncoder() { - return new BCryptPasswordEncoder(); - } - - @Bean - public UserDetailsService userDetailsService() { - //获取登录用户信息 - return new UserDetailsService() { - @Override - public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { - UmsMember member = memberService.getByUsername(username); - if(member!=null){ - return new MemberDetails(member); - } - throw new UsernameNotFoundException("用户名或密码错误"); - } - }; - } -} diff --git a/mall-portal/src/main/java/com/macro/mall/portal/service/UmsMemberService.java b/mall-portal/src/main/java/com/macro/mall/portal/service/UmsMemberService.java index 4a10e4d..15bb3d4 100644 --- a/mall-portal/src/main/java/com/macro/mall/portal/service/UmsMemberService.java +++ b/mall-portal/src/main/java/com/macro/mall/portal/service/UmsMemberService.java @@ -2,6 +2,7 @@ package com.macro.mall.portal.service; import com.macro.mall.common.api.CommonResult; import com.macro.mall.model.UmsMember; +import org.springframework.security.core.userdetails.UserDetails; import org.springframework.transaction.annotation.Transactional; /** @@ -45,4 +46,15 @@ public interface UmsMemberService { * 根据会员id修改会员积分 */ void updateIntegration(Long id,Integer integration); + + + /** + * 获取用户信息 + */ + UserDetails loadUserByUsername(String username); + + /** + * 登录后获取token + */ + String login(String username, String password); } diff --git a/mall-portal/src/main/java/com/macro/mall/portal/service/impl/UmsMemberServiceImpl.java b/mall-portal/src/main/java/com/macro/mall/portal/service/impl/UmsMemberServiceImpl.java index 99d4f59..0f46bd0 100644 --- a/mall-portal/src/main/java/com/macro/mall/portal/service/impl/UmsMemberServiceImpl.java +++ b/mall-portal/src/main/java/com/macro/mall/portal/service/impl/UmsMemberServiceImpl.java @@ -10,11 +10,19 @@ import com.macro.mall.model.UmsMemberLevelExample; import com.macro.mall.portal.domain.MemberDetails; import com.macro.mall.portal.service.RedisService; import com.macro.mall.portal.service.UmsMemberService; +import com.macro.mall.security.util.JwtTokenUtil; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; +import org.springframework.security.authentication.BadCredentialsException; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; +import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Service; import org.springframework.util.CollectionUtils; @@ -30,13 +38,16 @@ import java.util.Random; */ @Service public class UmsMemberServiceImpl implements UmsMemberService { + private static final Logger LOGGER = LoggerFactory.getLogger(UmsMemberServiceImpl.class); + @Autowired + private PasswordEncoder passwordEncoder; + @Autowired + private JwtTokenUtil jwtTokenUtil; @Autowired private UmsMemberMapper memberMapper; @Autowired private UmsMemberLevelMapper memberLevelMapper; @Autowired - private PasswordEncoder passwordEncoder; - @Autowired private RedisService redisService; @Value("${redis.key.prefix.authCode}") private String REDIS_KEY_PREFIX_AUTH_CODE; @@ -139,6 +150,33 @@ public class UmsMemberServiceImpl implements UmsMemberService { memberMapper.updateByPrimaryKeySelective(record); } + @Override + public UserDetails loadUserByUsername(String username) { + UmsMember member = getByUsername(username); + if(member!=null){ + return new MemberDetails(member); + } + throw new UsernameNotFoundException("用户名或密码错误"); + } + + @Override + public String login(String username, String password) { + String token = null; + //密码需要客户端加密后传递 + try { + UserDetails userDetails = loadUserByUsername(username); + if(!passwordEncoder.matches(password,userDetails.getPassword())){ + throw new BadCredentialsException("密码不正确"); + } + UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities()); + SecurityContextHolder.getContext().setAuthentication(authentication); + token = jwtTokenUtil.generateToken(userDetails); + } catch (AuthenticationException e) { + LOGGER.warn("登录异常:{}", e.getMessage()); + } + return token; + } + //对输入的验证码进行校验 private boolean verifyAuthCode(String authCode, String telephone){ if(StringUtils.isEmpty(authCode)){ diff --git a/mall-portal/src/main/resources/application.yml b/mall-portal/src/main/resources/application.yml index 736b461..877b016 100644 --- a/mall-portal/src/main/resources/application.yml +++ b/mall-portal/src/main/resources/application.yml @@ -9,6 +9,26 @@ mybatis: http: port: 8085 # http服务端口 +jwt: + tokenHeader: Authorization #JWT存储的请求头 + secret: mall-portal-secret #JWT加解密使用的密钥 + expiration: 604800 #JWT的超期限时间(60*60*24) + tokenHead: Bearer #JWT负载中拿到开头 +ignored: #安全路径白名单 + urls: + - /swagger-ui.html + - /swagger-resources/** + - /swagger/** + - /**/v2/api-docs + - /**/*.js + - /**/*.css + - /**/*.png + - /**/*.ico + - /webjars/springfox-swagger-ui/** + - /druid/** + - /actuator/** + - /sso/** + - /home/** # 自定义redis key redis: