81,122
社区成员




<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>ContractManagementSystem</title>
<link rel="stylesheet" type="text/css" href="css/login.css"/>
<script type="text/javascript" src="jquery/jquery-1.8.0.min.js"></script>
</head>
<body>
<div id="login_frame">
<p id="image_logo"><img src="../images/fly.png"></p>
<form id="login_form" method="post">
<p><label class="label_input">用户名</label><input type="text" id="loginName" class="text_field"/></p>
<p><label class="label_input">密码</label><input type="text" id="password" class="text_field"/></p>
</form>
<div id="login_control">
<input type="button" id="btn_login" value="登录" onclick="doLogin()"/>
<a id="forget_pwd" href="forget_pwd.html">忘记密码?</a>
</div>
</div>
<script>
function doLogin() {
var loginName = $('#loginName').val();
var password = $('#password').val();
$.ajax({
url: '/doLogin',
type: 'post',
data: {'loginName':loginName,'password':password},
success: function (data) {
if (data == "success") {
alert( '登录成功');
} else {
alert( '登录失败,详情咨询系统管理员!');
}
}
});
}
</script>
</body>
</html>
@RestController
public class LoginController {
@Autowired
UserService userService;
@PostMapping("doLogin")
public String doLogin(@RequestParam("loginName") String loginName, @RequestParam("password") String password) {
System.out.println("loginName={"+loginName+"},password={"+password+"}");
return "success";
}
}
@Configuration
public class AppSecurityConfigurer extends WebSecurityConfigurerAdapter {
@Autowired
private UserService userService;
@Autowired
private PasswordEncoder passwordEncoder; // 加密接口
@Autowired
private AuthenticationProvider authenticationProvider; // 用户认证接口
@Autowired
AppAuthenticationSuccessHandler appAuthenticationSuccessHandler; // 注入认证处理成功类
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
public AuthenticationProvider authenticationProvider() {
// 创建DaoAuthenticationProvider对象
DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
// 不要隐藏"用户未找到"的异常
provider.setHideUserNotFoundExceptions(false);
// 通过重写configure方法添加自定义的认证方式。
provider.setUserDetailsService(userService);
// 设置密码加密程序认证
provider.setPasswordEncoder(passwordEncoder);
return provider;
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
System.out.println("AppSecurityConfigurer configure auth......");
// 设置自定义的认证方式。
auth.authenticationProvider(authenticationProvider);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
System.out.println("AppSecurityConfigurer configure http......");
http.authorizeRequests()
// spring-security 5.0 之后需要过滤静态资源
.antMatchers("/login", "/css/**", "/js/**", "/jquery/**", "/images/*").permitAll()
.antMatchers("/add").hasAnyRole("USER", "ADMIN")
.antMatchers("/list").hasRole("ADMIN")
.anyRequest().authenticated()
.and()
.formLogin().loginPage("/login").successHandler(appAuthenticationSuccessHandler)
//.usernameParameter("loginName").passwordParameter("password")
.and()
.logout().logoutSuccessUrl("/login").permitAll()
.and()
.exceptionHandling().accessDeniedPage("/accessDenied");
}
@Component
public class AppAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
// Spring Security 通过RedirectStrategy对象负责所有重定向事务
private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
// 通过determineTargetUrl方法返回需要跳转的url
String targetUrl = determineTargetUrl(authentication);
// 重定向请求到指定的url
redirectStrategy.sendRedirect(request, response, targetUrl);
clearAuthenticationAttributes(request);
}
protected void clearAuthenticationAttributes(HttpServletRequest request) {
HttpSession session = request.getSession(false);
if (session == null) {
return;
}
session.removeAttribute(WebAttributes.AUTHENTICATION_EXCEPTION);
}
/*
* 从Authentication对象中提取角色提取当前登录用户的角色,并根据其角色返回适当的URL。
*/
protected String determineTargetUrl(Authentication authentication) {
String url = "";
// 获取当前登录用户的角色权限集合
Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
List<String> roles = new ArrayList<>();
// 将角色名称添加到List集合
for (GrantedAuthority a : authorities) {
roles.add(a.getAuthority());
}
// 判断不同角色跳转到不同的url
if (roles.contains("ROLE_USER")) {
url = "/list";
} else if (roles.contains("ROLE_ADMIN")) {
url = "/add";
} else {
url = "/accessDenied";
}
System.out.println("determineTargetUrl-----url = " + url);
return url;
}
public void setRedirectStrategy(RedirectStrategy redirectStrategy) {
this.redirectStrategy = redirectStrategy;
}
protected RedirectStrategy getRedirectStrategy() {
return redirectStrategy;
}
}
@Service
public class UserService implements UserDetailsService {
@Resource
UserRepository userRepository;
@Override
public UserDetails loadUserByUsername(String loginName) throws UsernameNotFoundException {
UUser uuser = userRepository.findByLoginName(loginName);
if (uuser == null) {
throw new UsernameNotFoundException("用户名不存在");
}
List<GrantedAuthority> authorities = new ArrayList<>(); //GrantedAuthority代表赋予当前用户的权限
List<Role> roles = uuser.getRoles();
for (Role role : roles) {
// 将关联对象Role的authority属性保存为用户的认证权限
authorities.add(new SimpleGrantedAuthority(role.getAuthority()));
}
return new User(uuser.getLoginName(), uuser.getPassword(), authorities);
}
}