Skip to content

Commit

Permalink
更新登录请求方式
Browse files Browse the repository at this point in the history
  • Loading branch information
lenve committed Mar 29, 2020
1 parent 79b0fd5 commit 8444181
Show file tree
Hide file tree
Showing 6 changed files with 119 additions and 101 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
package org.javaboy.vhr.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
* @作者 江南一点雨
* @微信公众号 江南一点雨
* @网站 http://www.javaboy.org
* @微信 a_java_boy
* @GitHub https://github.com/lenve
* @Gitee https://gitee.com/lenve
*/
public class LoginFilter extends UsernamePasswordAuthenticationFilter {
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
if (!request.getMethod().equals("POST")) {
throw new AuthenticationServiceException(
"Authentication method not supported: " + request.getMethod());
}
String verify_code = (String) request.getSession().getAttribute("verify_code");
if (request.getContentType().equals(MediaType.APPLICATION_JSON_VALUE) || request.getContentType().equals(MediaType.APPLICATION_JSON_UTF8_VALUE)) {
Map<String, String> loginData = new HashMap<>();
try {
loginData = new ObjectMapper().readValue(request.getInputStream(), Map.class);
String code = loginData.get("code");
checkCode(response, code, verify_code);
} catch (IOException e) {
}
String username = loginData.get(getUsernameParameter());
String password = loginData.get(getPasswordParameter());
if (username == null) {
username = "";
}
if (password == null) {
password = "";
}
username = username.trim();
UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(
username, password);
setDetails(request, authRequest);
return this.getAuthenticationManager().authenticate(authRequest);
} else {
checkCode(response, request.getParameter("code"), verify_code);
return super.attemptAuthentication(request, response);
}
}

public void checkCode(HttpServletResponse resp, String code, String verify_code) {
if (code == null || verify_code == null || "".equals(code) || !verify_code.toLowerCase().equals(code.toLowerCase())) {
//验证码不正确
throw new AuthenticationServiceException("验证码不正确");
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,6 @@
* @GitHub https://github.com/lenve
* @博客 http://wangsong.blog.csdn.net
* @网站 http://www.javaboy.org
* @时间 2019-09-20 8:25
*/
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
Expand All @@ -47,8 +46,6 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
CustomFilterInvocationSecurityMetadataSource customFilterInvocationSecurityMetadataSource;
@Autowired
CustomUrlDecisionManager customUrlDecisionManager;
@Autowired
VerificationCodeFilter verificationCodeFilter;

@Bean
PasswordEncoder passwordEncoder() {
Expand All @@ -62,14 +59,56 @@ protected void configure(AuthenticationManagerBuilder auth) throws Exception {

@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/login","/css/**","/js/**","/index.html","/img/**","/fonts/**","/favicon.ico","/verifyCode");
web.ignoring().antMatchers("/css/**","/js/**","/index.html","/img/**","/fonts/**","/favicon.ico","/verifyCode");
}

@Bean
LoginFilter loginFilter() throws Exception {
LoginFilter loginFilter = new LoginFilter();
loginFilter.setAuthenticationSuccessHandler(new AuthenticationSuccessHandler() {
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
response.setContentType("application/json;charset=utf-8");
PrintWriter out = response.getWriter();
Hr hr = (Hr) authentication.getPrincipal();
hr.setPassword(null);
RespBean ok = RespBean.ok("登录成功!", hr);
String s = new ObjectMapper().writeValueAsString(ok);
out.write(s);
out.flush();
out.close();
}
});
loginFilter.setAuthenticationFailureHandler(new AuthenticationFailureHandler() {
@Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
response.setContentType("application/json;charset=utf-8");
PrintWriter out = response.getWriter();
RespBean respBean = RespBean.error(exception.getMessage());
if (exception instanceof LockedException) {
respBean.setMsg("账户被锁定,请联系管理员!");
} else if (exception instanceof CredentialsExpiredException) {
respBean.setMsg("密码过期,请联系管理员!");
} else if (exception instanceof AccountExpiredException) {
respBean.setMsg("账户过期,请联系管理员!");
} else if (exception instanceof DisabledException) {
respBean.setMsg("账户被禁用,请联系管理员!");
} else if (exception instanceof BadCredentialsException) {
respBean.setMsg("用户名或者密码输入错误,请重新输入!");
}
out.write(new ObjectMapper().writeValueAsString(respBean));
out.flush();
out.close();
}
});
loginFilter.setAuthenticationManager(authenticationManagerBean());
loginFilter.setFilterProcessesUrl("/doLogin");
return loginFilter;
}

@Override
protected void configure(HttpSecurity http) throws Exception {
http.addFilterBefore(verificationCodeFilter, UsernamePasswordAuthenticationFilter.class);
http.authorizeRequests()
// .anyRequest().authenticated()
.withObjectPostProcessor(new ObjectPostProcessor<FilterSecurityInterceptor>() {
@Override
public <O extends FilterSecurityInterceptor> O postProcess(O object) {
Expand All @@ -79,49 +118,6 @@ public <O extends FilterSecurityInterceptor> O postProcess(O object) {
}
})
.and()
.formLogin()
.usernameParameter("username")
.passwordParameter("password")
.loginProcessingUrl("/doLogin")
.loginPage("/login")
.successHandler(new AuthenticationSuccessHandler() {
@Override
public void onAuthenticationSuccess(HttpServletRequest req, HttpServletResponse resp, Authentication authentication) throws IOException, ServletException {
resp.setContentType("application/json;charset=utf-8");
PrintWriter out = resp.getWriter();
Hr hr = (Hr) authentication.getPrincipal();
hr.setPassword(null);
RespBean ok = RespBean.ok("登录成功!", hr);
String s = new ObjectMapper().writeValueAsString(ok);
out.write(s);
out.flush();
out.close();
}
})
.failureHandler(new AuthenticationFailureHandler() {
@Override
public void onAuthenticationFailure(HttpServletRequest req, HttpServletResponse resp, AuthenticationException exception) throws IOException, ServletException {
resp.setContentType("application/json;charset=utf-8");
PrintWriter out = resp.getWriter();
RespBean respBean = RespBean.error("登录失败!");
if (exception instanceof LockedException) {
respBean.setMsg("账户被锁定,请联系管理员!");
} else if (exception instanceof CredentialsExpiredException) {
respBean.setMsg("密码过期,请联系管理员!");
} else if (exception instanceof AccountExpiredException) {
respBean.setMsg("账户过期,请联系管理员!");
} else if (exception instanceof DisabledException) {
respBean.setMsg("账户被禁用,请联系管理员!");
} else if (exception instanceof BadCredentialsException) {
respBean.setMsg("用户名或者密码输入错误,请重新输入!");
}
out.write(new ObjectMapper().writeValueAsString(respBean));
out.flush();
out.close();
}
})
.permitAll()
.and()
.logout()
.logoutSuccessHandler(new LogoutSuccessHandler() {
@Override
Expand Down Expand Up @@ -152,5 +148,6 @@ public void commence(HttpServletRequest req, HttpServletResponse resp, Authentic
out.close();
}
});
http.addFilterAt(loginFilter(), UsernamePasswordAuthenticationFilter.class);
}
}

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
Expand All @@ -27,10 +28,11 @@ public RespBean login() {
}

@GetMapping("/verifyCode")
public void verifyCode(HttpSession session, HttpServletResponse resp) throws IOException {
public void verifyCode(HttpServletRequest request, HttpServletResponse resp) throws IOException {
VerificationCode code = new VerificationCode();
BufferedImage image = code.getImage();
String text = code.getText();
HttpSession session = request.getSession(true);
session.setAttribute("verify_code", text);
VerificationCode.output(image,resp.getOutputStream());
}
Expand Down
4 changes: 2 additions & 2 deletions vhr/vhrserver/vhr-web/src/main/resources/application.yml
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,11 @@ spring:
rabbitmq:
username: guest
password: guest
host: 192.168.91.128
host: 127.0.0.1
publisher-confirms: true
publisher-returns: true
redis:
host: 192.168.91.128
host: 127.0.0.1
database: 0
port: 6379
password: 123
Expand Down
4 changes: 2 additions & 2 deletions vuehr/src/views/Login.vue
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@
this.$refs.loginForm.validate((valid) => {
if (valid) {
this.loading = true;
this.postKeyValueRequest('/doLogin', this.loginForm).then(resp => {
this.postRequest('/doLogin', this.loginForm).then(resp => {
this.loading = false;
if (resp) {
this.$store.commit('INIT_CURRENTHR', resp.obj);
Expand Down Expand Up @@ -104,4 +104,4 @@
display: flex;
align-items: center;
}
</style>
</style>

0 comments on commit 8444181

Please sign in to comment.