zhh 6 лет назад
Родитель
Сommit
f75835cee4

+ 21 - 0
mall-portal/src/main/java/com/macro/mall/portal/component/GoAccessDeniedHandler.java

@@ -0,0 +1,21 @@
+package com.macro.mall.portal.component;
+
+import org.springframework.security.access.AccessDeniedException;
+import org.springframework.security.web.access.AccessDeniedHandler;
+
+import javax.servlet.ServletException;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.io.IOException;
+
+/**
+ * Created by macro on 2018/8/6.
+ */
+public class GoAccessDeniedHandler implements AccessDeniedHandler{
+    @Override
+    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
+        response.setHeader("Content-Type", "application/json;charset=utf-8");
+        response.getWriter().print("{\"code\":401,\"message\":\""+"未认证:"+accessDeniedException.getMessage()+"\"}");
+        response.getWriter().flush();
+    }
+}

+ 21 - 0
mall-portal/src/main/java/com/macro/mall/portal/component/GoAuthenticationEntryPoint.java

@@ -0,0 +1,21 @@
+package com.macro.mall.portal.component;
+
+import org.springframework.security.core.AuthenticationException;
+import org.springframework.security.web.AuthenticationEntryPoint;
+
+import javax.servlet.ServletException;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.io.IOException;
+
+/**
+ * Created by macro on 2018/8/6.
+ */
+public class GoAuthenticationEntryPoint implements AuthenticationEntryPoint {
+    @Override
+    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
+        response.setHeader("Content-Type", "application/json;charset=utf-8");
+        response.getWriter().print("{\"code\":403,\"message\":\""+"未授权:"+authException.getMessage()+"\"}");
+        response.getWriter().flush();
+    }
+}

+ 21 - 0
mall-portal/src/main/java/com/macro/mall/portal/component/GoAuthenticationFailureHandler.java

@@ -0,0 +1,21 @@
+package com.macro.mall.portal.component;
+
+import org.springframework.security.core.AuthenticationException;
+import org.springframework.security.web.authentication.AuthenticationFailureHandler;
+
+import javax.servlet.ServletException;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.io.IOException;
+
+/**
+ * Created by macro on 2018/8/6.
+ */
+public class GoAuthenticationFailureHandler implements AuthenticationFailureHandler {
+    @Override
+    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
+        response.setHeader("Content-Type", "application/json;charset=utf-8");
+        response.getWriter().print("{\"code\":500,\"message\":\""+"登录失败:"+exception.getMessage()+"\"}");
+        response.getWriter().flush();
+    }
+}

+ 21 - 0
mall-portal/src/main/java/com/macro/mall/portal/component/GoAuthenticationSuccessHandler.java

@@ -0,0 +1,21 @@
+package com.macro.mall.portal.component;
+
+import org.springframework.security.core.Authentication;
+import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
+
+import javax.servlet.ServletException;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.io.IOException;
+
+/**
+ * Created by macro on 2018/8/6.
+ */
+public class GoAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
+    @Override
+    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
+        response.setHeader("Content-Type", "application/json;charset=utf-8");
+        response.getWriter().print("{\"code\":200,\"message\":\"登录成功\"}");
+        response.getWriter().flush();
+    }
+}

+ 21 - 0
mall-portal/src/main/java/com/macro/mall/portal/component/GoLogoutSuccessHandler.java

@@ -0,0 +1,21 @@
+package com.macro.mall.portal.component;
+
+import org.springframework.security.core.Authentication;
+import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
+
+import javax.servlet.ServletException;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.io.IOException;
+
+/**
+ * Created by macro on 2018/8/6.
+ */
+public class GoLogoutSuccessHandler implements LogoutSuccessHandler {
+    @Override
+    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
+        response.setHeader("Content-Type", "application/json;charset=utf-8");
+        response.getWriter().print("{\"code\":200,\"message\":\"已注销\"}");
+        response.getWriter().flush();
+    }
+}

+ 26 - 1
mall-portal/src/main/java/com/macro/mall/portal/config/SecurityConfig.java

@@ -1,6 +1,7 @@
 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;
@@ -47,7 +48,31 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
                 .anyRequest()// 除上面外的所有请求全部需要鉴权认证
                 .authenticated()
                 .and()
-                .csrf().disable();
+                .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

+ 3 - 16
mall-portal/src/main/java/com/macro/mall/portal/controller/UmsMemberController.java

@@ -22,12 +22,6 @@ import org.springframework.web.bind.annotation.ResponseBody;
 public class UmsMemberController {
     @Autowired
     private UmsMemberService memberService;
-    @ApiOperation("登录")
-    @RequestMapping(value = "/login", method = RequestMethod.POST)
-    @ResponseBody
-    public Object login(@RequestParam String username, @RequestParam String password) {
-        return memberService.login(username,password);
-    }
 
     @ApiOperation("注册")
     @RequestMapping(value = "/register", method = RequestMethod.POST)
@@ -36,8 +30,8 @@ public class UmsMemberController {
                            @RequestParam String password,
                            @RequestParam String telephone,
                            @RequestParam String authCode) {
-        UmsMember member = memberService.register(username,password,telephone,authCode);
-        if(member!=null){
+        UmsMember member = memberService.register(username, password, telephone, authCode);
+        if (member != null) {
             return new CommonResult().success(member);
         }
         return new CommonResult().failed();
@@ -56,13 +50,6 @@ public class UmsMemberController {
     public Object updatePassword(@RequestParam String telephone,
                                  @RequestParam String password,
                                  @RequestParam String authCode) {
-        return null;
-    }
-
-    @ApiOperation("登出操作")
-    @RequestMapping(value = "/logout", method = RequestMethod.POST)
-    @ResponseBody
-    public Object logout() {
-        return null;
+        return memberService.updatePassword(telephone,password,authCode);
     }
 }

+ 5 - 4
mall-portal/src/main/java/com/macro/mall/portal/service/UmsMemberService.java

@@ -21,12 +21,13 @@ public interface UmsMemberService {
     UmsMember register(String username, String password, String telephone, String authCode);
 
     /**
-     * 登录操作
+     * 生成验证码
      */
-    CommonResult login(String username, String password);
+    CommonResult generateAuthCode(String telephone);
 
     /**
-     * 生成验证
+     * 修改密
      */
-    CommonResult generateAuthCode(String telephone);
+    @Transactional
+    CommonResult updatePassword(String telephone, String password, String authCode);
 }

+ 21 - 22
mall-portal/src/main/java/com/macro/mall/portal/service/impl/UmsMemberServiceImpl.java

@@ -8,19 +8,14 @@ import com.macro.mall.model.UmsMemberLevel;
 import com.macro.mall.model.UmsMemberLevelExample;
 import com.macro.mall.portal.domain.CommonResult;
 import com.macro.mall.portal.service.UmsMemberService;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
 import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.security.authentication.AuthenticationManager;
-import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
 import org.springframework.security.authentication.encoding.PasswordEncoder;
-import org.springframework.security.core.AuthenticationException;
-import org.springframework.security.core.context.SecurityContextHolder;
 import org.springframework.stereotype.Service;
 import org.springframework.util.CollectionUtils;
 
 import java.util.Date;
 import java.util.List;
+import java.util.Random;
 
 /**
  * 会员管理Service实现类
@@ -34,9 +29,6 @@ public class UmsMemberServiceImpl implements UmsMemberService {
     private UmsMemberLevelMapper memberLevelMapper;
     @Autowired
     private PasswordEncoder passwordEncoder;
-    @Autowired
-    private AuthenticationManager authenticationManager;
-    private static final Logger LOGGER = LoggerFactory.getLogger(UmsMemberServiceImpl.class);
 
     @Override
     public UmsMember getByUsername(String username) {
@@ -79,22 +71,29 @@ public class UmsMemberServiceImpl implements UmsMemberService {
     }
 
     @Override
-    public CommonResult login(String username, String password) {
-        CommonResult result;
-        UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(username, passwordEncoder.encodePassword(password, null));
-        try {
-            authenticationManager.authenticate(authentication);
-            SecurityContextHolder.getContext().setAuthentication(authentication);
-            result = new CommonResult().success("登录成功");
-        } catch (AuthenticationException e) {
-            LOGGER.warn("登录异常:{}", e.getMessage());
-            result = new CommonResult().failed("登录异常:"+e.getMessage());
+    public CommonResult generateAuthCode(String telephone) {
+        StringBuilder sb = new StringBuilder();
+        Random random = new Random();
+        for(int i=0;i<6;i++){
+            sb.append(random.nextInt(10));
         }
-        return result;
+        // TODO: 2018/8/6 验证码进行存储
+        return new CommonResult().success("获取验证码成功",sb.toString());
     }
 
     @Override
-    public CommonResult generateAuthCode(String telephone) {
-        return null;
+    public CommonResult updatePassword(String telephone, String password, String authCode) {
+        UmsMemberExample example = new UmsMemberExample();
+        example.createCriteria().andPhoneEqualTo(telephone);
+        List<UmsMember> memberList = memberMapper.selectByExample(example);
+        if(CollectionUtils.isEmpty(memberList)){
+            return new CommonResult().failed("该账号不存在");
+        }
+        // TODO: 2018/8/6 验证验证码
+        UmsMember umsMember = memberList.get(0);
+        umsMember.setPassword(passwordEncoder.encodePassword(password,null));
+        memberMapper.updateByPrimaryKeySelective(umsMember);
+        return new CommonResult().success("密码修改成功",null);
     }
+
 }