Search in sources :

Example 1 with AnonymousAccess

use of com.albedo.java.common.core.annotation.AnonymousAccess in project albedo by somowhere.

the class SecurityUtil method getAnonymousUrl.

public static Map<String, Set<String>> getAnonymousUrl(Map<RequestMappingInfo, HandlerMethod> handlerMethodMap) {
    Map<String, Set<String>> anonymousUrls = new HashMap<>(6);
    Set<String> get = new HashSet<>();
    Set<String> post = new HashSet<>();
    Set<String> put = new HashSet<>();
    Set<String> patch = new HashSet<>();
    Set<String> delete = new HashSet<>();
    Set<String> all = new HashSet<>();
    for (Map.Entry<RequestMappingInfo, HandlerMethod> infoEntry : handlerMethodMap.entrySet()) {
        HandlerMethod handlerMethod = infoEntry.getValue();
        AnonymousAccess anonymousAccess = handlerMethod.getMethodAnnotation(AnonymousAccess.class);
        if (null != anonymousAccess) {
            List<RequestMethod> requestMethods = new ArrayList<>(infoEntry.getKey().getMethodsCondition().getMethods());
            RequestMethodEnum request = RequestMethodEnum.find(requestMethods.size() == 0 ? RequestMethodEnum.ALL.getType() : requestMethods.get(0).name());
            switch(Objects.requireNonNull(request)) {
                case GET:
                    get.addAll(getPatterns(infoEntry));
                    break;
                case POST:
                    post.addAll(getPatterns(infoEntry));
                    break;
                case PUT:
                    put.addAll(getPatterns(infoEntry));
                    break;
                case PATCH:
                    patch.addAll(getPatterns(infoEntry));
                    break;
                case DELETE:
                    delete.addAll(getPatterns(infoEntry));
                    break;
                default:
                    all.addAll(getPatterns(infoEntry));
                    break;
            }
        }
    }
    anonymousUrls.put(RequestMethodEnum.GET.getType(), get);
    anonymousUrls.put(RequestMethodEnum.POST.getType(), post);
    anonymousUrls.put(RequestMethodEnum.PUT.getType(), put);
    anonymousUrls.put(RequestMethodEnum.PATCH.getType(), patch);
    anonymousUrls.put(RequestMethodEnum.DELETE.getType(), delete);
    anonymousUrls.put(RequestMethodEnum.ALL.getType(), all);
    return anonymousUrls;
}
Also used : RequestMappingInfo(org.springframework.web.servlet.mvc.method.RequestMappingInfo) AnonymousAccess(com.albedo.java.common.core.annotation.AnonymousAccess) RequestMethod(org.springframework.web.bind.annotation.RequestMethod) HandlerMethod(org.springframework.web.method.HandlerMethod) RequestMethodEnum(com.albedo.java.common.security.enums.RequestMethodEnum)

Example 2 with AnonymousAccess

use of com.albedo.java.common.core.annotation.AnonymousAccess in project albedo by somowhere.

the class AccoutJwtResource method logout.

/**
 * @return org.springframework.http.ResponseEntity
 * @description 登出
 * @Param: [authHeader, request, response]
 * @author somewhere
 * @date 2020/5/30
 */
@AnonymousAccess
@GetMapping(value = "/logout")
@Operation(summary = "登出")
public ResponseEntity<Result> logout(@RequestHeader(value = HttpHeaders.AUTHORIZATION, required = false) String authHeader, HttpServletRequest request, HttpServletResponse response) {
    String tokenValue = authHeader.replace("Bearer ", StrUtil.EMPTY).trim();
    RedisUtil.delete(tokenValue);
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    if (auth != null) {
        new SecurityContextLogoutHandler().logout(request, response, auth);
    }
    WebUtil.removeCookie(response, HttpHeaders.AUTHORIZATION);
    request.getSession().invalidate();
    return ResponseEntityBuilder.buildOk("退出登录成功");
}
Also used : SecurityContextLogoutHandler(org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler) Authentication(org.springframework.security.core.Authentication) AnonymousAccess(com.albedo.java.common.core.annotation.AnonymousAccess) Operation(io.swagger.v3.oas.annotations.Operation)

Example 3 with AnonymousAccess

use of com.albedo.java.common.core.annotation.AnonymousAccess in project albedo by somowhere.

the class AccoutJwtResource method authorize.

/**
 * 功能描述: 认证授权
 */
@AnonymousAccess
@PostMapping(SecurityConstants.AUTHENTICATE_URL)
@Operation(summary = "认证授权")
public ResponseEntity<Result> authorize(@Valid @RequestBody LoginVo loginVo) {
    Date canLoginDate = RedisUtil.getCacheObject(SecurityConstants.DEFAULT_LOGIN_AFTER_24_KEY + loginVo.getUsername());
    if (canLoginDate != null) {
        return ResponseEntityBuilder.buildFail(HttpStatus.UNAUTHORIZED, "您的账号在" + DateUtil.format(canLoginDate) + "后才可登录");
    }
    if (!SpringContextHolder.isDevelopment()) {
        LoginUtil.checkCode(loginVo);
    }
    try {
        String s = PasswordDecoderFilter.decryptAes(loginVo.getPassword(), applicationProperties.getSecurity().getEncodeKey());
        loginVo.setPassword(s.trim());
    } catch (Exception e) {
    }
    UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginVo.getUsername(), loginVo.getPassword());
    String keyLoginCount = SecurityConstants.DEFAULT_LOGIN_KEY + loginVo.getUsername();
    try {
        Authentication authentication = this.authenticationManager.authenticate(authenticationToken);
        SecurityContextHolder.getContext().setAuthentication(authentication);
        boolean rememberMe = (loginVo.getRememberMe() == null) ? false : loginVo.getRememberMe();
        String jwt = tokenProvider.createToken(authentication, rememberMe);
        log.info("jwt:{}", jwt);
        RedisUtil.delete(keyLoginCount);
        return ResponseEntityBuilder.buildOkData(new LinkedHashMap<String, Object>() {

            {
                put("access_token", jwt);
                put("expires_in", tokenProvider.getExpirationDateSecondsFromToken(jwt));
            }
        });
    } catch (AuthenticationException ae) {
        log.warn("Authentication exception trace: {}", ae);
        String msg = ae.getMessage();
        if (ae instanceof BadCredentialsException) {
            Integer cacheObject = RedisUtil.getCacheObject(keyLoginCount);
            if (cacheObject == null) {
                cacheObject = 1;
            }
            msg = "密码错误,请重试";
            boolean level1 = cacheObject >= 5 && cacheObject < 9;
            boolean level2 = cacheObject == 9;
            boolean level3 = cacheObject > 9;
            if (level1) {
                msg = "您还剩" + (10 - cacheObject) + "次密码输入机会,建议点击‘忘记密码’";
            } else if (level2) {
                msg = "您还剩1次密码输入机会,再次错误,您的账号将被暂时锁定24小时,24小时内禁止登录";
            } else if (level3) {
                msg = "您密码错误次数已超过10次,您的账号将被暂时锁定24小时,建议点击‘忘记密码’,凭手机号码重置密码,24小时后再尝试登录";
                cacheObject = 0;
            // RedisUtil.setCacheObject(SecurityConstants.DEFAULT_LOGIN_AFTER_24_KEY
            // +loginVo.getUsername(),
            // DateUtil.addDays(PublicUtil.getCurrentDate(), 1), 1,
            // TimeUnit.DAYS);
            }
            RedisUtil.setCacheObject(keyLoginCount, 1 + cacheObject);
        }
        return ResponseEntityBuilder.buildFail(HttpStatus.UNAUTHORIZED, msg);
    }
}
Also used : AuthenticationException(org.springframework.security.core.AuthenticationException) Authentication(org.springframework.security.core.Authentication) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) Date(java.util.Date) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) AuthenticationException(org.springframework.security.core.AuthenticationException) AnonymousAccess(com.albedo.java.common.core.annotation.AnonymousAccess) Operation(io.swagger.v3.oas.annotations.Operation)

Example 4 with AnonymousAccess

use of com.albedo.java.common.core.annotation.AnonymousAccess in project albedo by somowhere.

the class AccoutResource method valicode.

@AnonymousAccess
@GetMapping(path = "/code/{randomStr}", produces = MediaType.IMAGE_JPEG_VALUE)
@Operation(summary = "获取验证码")
public void valicode(@PathVariable("randomStr") String randomStr, HttpServletResponse response) throws IOException {
    ArgumentAssert.notEmpty(randomStr, "机器码不能为空");
    response.setHeader("Cache-Control", "no-store, no-cache");
    response.setHeader("Transfer-Encoding", "JPG");
    response.setContentType("image/jpeg");
    ArithmeticCaptcha captcha = new ArithmeticCaptcha(DEFAULT_IMAGE_WIDTH, DEFAULT_IMAGE_HEIGHT);
    String result = captcha.text();
    RedisUtil.setCacheString(CommonConstants.DEFAULT_CODE_KEY + randomStr, result, CommonConstants.DEFAULT_IMAGE_EXPIRE, TimeUnit.SECONDS);
    // 创建输出流
    ServletOutputStream out = response.getOutputStream();
    captcha.out(out);
    IoUtil.close(out);
}
Also used : ArithmeticCaptcha(com.pig4cloud.captcha.ArithmeticCaptcha) ServletOutputStream(javax.servlet.ServletOutputStream) AnonymousAccess(com.albedo.java.common.core.annotation.AnonymousAccess) Operation(io.swagger.v3.oas.annotations.Operation)

Example 5 with AnonymousAccess

use of com.albedo.java.common.core.annotation.AnonymousAccess in project albedo by somowhere.

the class AliPayResource method notify.

@RequestMapping("/notify")
@AnonymousAccess
@SuppressWarnings("all")
@Operation(hidden = true, summary = "支付异步通知(要公网访问),接收异步通知,检查通知内容app_id、out_trade_no、total_amount是否与请求中的一致,根据trade_status进行后续业务处理")
public ResponseEntity<Object> notify(HttpServletRequest request) {
    AlipayConfigDo alipay = alipayService.find();
    Map<String, String[]> parameterMap = request.getParameterMap();
    // 内容验签,防止黑客篡改参数
    if (alipayUtils.rsaCheck(request, alipay)) {
        // 交易状态
        String tradeStatus = new String(request.getParameter("trade_status").getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
        // 商户订单号
        String outTradeNo = new String(request.getParameter("out_trade_no").getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
        // 支付宝交易号
        String tradeNo = new String(request.getParameter("trade_no").getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
        // 付款金额
        String totalAmount = new String(request.getParameter("total_amount").getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
        // 验证
        if (tradeStatus.equals(AliPayStatusEnum.SUCCESS.getValue()) || tradeStatus.equals(AliPayStatusEnum.FINISHED.getValue())) {
        // 验证通过后应该根据业务需要处理订单
        }
        return new ResponseEntity<>(HttpStatus.OK);
    }
    return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
Also used : ResponseEntity(org.springframework.http.ResponseEntity) AlipayConfigDo(com.albedo.java.modules.tool.domain.AlipayConfigDo) AnonymousAccess(com.albedo.java.common.core.annotation.AnonymousAccess) Operation(io.swagger.v3.oas.annotations.Operation)

Aggregations

AnonymousAccess (com.albedo.java.common.core.annotation.AnonymousAccess)6 Operation (io.swagger.v3.oas.annotations.Operation)5 AlipayConfigDo (com.albedo.java.modules.tool.domain.AlipayConfigDo)2 ResponseEntity (org.springframework.http.ResponseEntity)2 Authentication (org.springframework.security.core.Authentication)2 RequestMethodEnum (com.albedo.java.common.security.enums.RequestMethodEnum)1 ArithmeticCaptcha (com.pig4cloud.captcha.ArithmeticCaptcha)1 Date (java.util.Date)1 ServletOutputStream (javax.servlet.ServletOutputStream)1 BadCredentialsException (org.springframework.security.authentication.BadCredentialsException)1 UsernamePasswordAuthenticationToken (org.springframework.security.authentication.UsernamePasswordAuthenticationToken)1 AuthenticationException (org.springframework.security.core.AuthenticationException)1 SecurityContextLogoutHandler (org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler)1 RequestMethod (org.springframework.web.bind.annotation.RequestMethod)1 HandlerMethod (org.springframework.web.method.HandlerMethod)1 RequestMappingInfo (org.springframework.web.servlet.mvc.method.RequestMappingInfo)1