Novices use security everyday

Painful painful

1. The first is cross-domain issues , if your project is separated from the front and back. Then there must be disgusting cross-domain issues. But I usually use a more conventional method to achieve cross-domain, that is, configure cors cross-domain in spring boot. If you have any friends in need, you can read another blog of mine. Back to the topic: If you use security with the front and back ends separated, you will report a cross-domain error! I? ? ? ? ? Am I configured for cross-domain? Why do you still remind me of cross-domain issues? I am very distressed. I wonder if my cross-domain approach is too low So I changed the cross-domain method countless times, from the background to the foreground, from axios to jsonp, no, in the end, I found that spring security is still blaming.
You need to configure it in the ** void configure (HttpSecurity http) method
Insert picture description here

in your MyWebSecurityConfig file . That ’s right. You need to configure this cor () configuration. Otherwise you can never cross domain! 2. Then, after you have written the code, you want to test if there is anything wrong. You change it, change the permissions from login success to login failure, and then find out? ? ? Not good? So you go directly to the backend address, alasBold style **
this is all right? ? Why, I can do this, but the front and back ends can't be separated? Insert picture description here
Just returned a piece of html to you and let you log in again? Hahahaha, that's how I did it, it was too painful, after two or three days of change. Suddenly, my friend told me that the difference between these two requests is that one will send session information, while the other will not. I'm ashamed! This is the case, so I found that if you send a normal request when the front and back ends are separated, the session carried each time is different! That's right, it's because of this, so even after you log in, you can't do it when you send the request again, because the session of the request you sent the second time doesn't have information about whether you log in. After the reason is clear, it is easy to handle.
Insert picture description here
Import axios in the main.js of your vue project, and then set his axios.defaults.withCredentials configuration to true. If you are interested in this configuration, please take a look. You use the same session. Come visit again now!
Insert picture description hereInsert picture description here
Here we are requesting http: // localhost: 8000 / admin / hello, and we log in with the authority of this admin (system administrator). So you can return a hello admin message!
At this point you are basically done. Then attach the code.

@Override
protected void configure(HttpSecurity http) throws Exception {
	http.cors().and().authorizeRequests()
	.antMatchers("/admin/**")
	.hasRole("ADMIN")
	.antMatchers("/user/**")
	.access("hasAnyRole('ADMIN','USER')")
	.antMatchers("/db/**")
	.access("hasRole('ADMIN') and hasRole('DBA')")
	.anyRequest()
	.authenticated()
	.and()
	.formLogin()
	//.loginPage("/login_page")
	.successHandler(new AuthenticationSuccessHandler () {

		@Override
		public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
				Authentication auth) throws IOException, ServletException {
			// TODO Auto-generated method stub
			Object pricipal = auth.getPrincipal();
			response.setContentType("application/json;charset=utf-8");
			PrintWriter out = response.getWriter();
			response.setStatus(200);
			Map<String, Object> map = new HashMap<>();
			map.put("status", 200);
			map.put("msg", pricipal);
			ObjectMapper om = new ObjectMapper();
			out.write(om.writeValueAsString(map));
			out.flush();
			out.close();
		}
		
	})
	
	.failureHandler(new AuthenticationFailureHandler () {

		@Override
		public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
				AuthenticationException e) throws IOException, ServletException {
			// TODO Auto-generated method stub
			response.setContentType("application/json;charset=utf-8");
			PrintWriter out = response.getWriter();
			response.setStatus(200);
			Map<String, Object> map = new HashMap<>();
			map.put("status", 401);
			if (e instanceof LockedException) {
				map.put("msg", "账户被锁定,登陆失败");
			} else if (e instanceof BadCredentialsException) {
				map.put("msg", "账户名或密码输入错误,登陆失败");
			} else if (e instanceof DisabledException) {
				map.put("msg", "账户被禁用,登陆失败");
			} else if (e instanceof AccountExpiredException) {
				map.put("msg", "账户已过期,登陆失败");
			} else if (e instanceof CredentialsExpiredException) {
				map.put("msg", "密码过期,登陆失败");
			} else {
				map.put("msg", "登陆失败");
			}
			
			ObjectMapper om = new ObjectMapper();
			out.write(om.writeValueAsString(map));
			out.flush();
			out.close();
		}
		
	})
	.loginProcessingUrl("/login")
	.usernameParameter("username")
	.passwordParameter("password")
	.permitAll()
	.and()
	.csrf()
	.disable()
	.exceptionHandling()
	.accessDeniedHandler(getAccessDeniedHandler());
	}

//////////////////////////////////////

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import xxp.entity.User;
import xxp.mapper.UserMapper;

@Service
public class UserService implements UserDetailsService{
	
	@Autowired
	private UserMapper usermapper;

	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		// TODO Auto-generated method stub
		User user = usermapper.loadUserByUsername(username);
		if (user == null) {
			throw new UsernameNotFoundException("账户不存在");
		}
		// 通过id查找角色
		user.setRoles(usermapper.getUserRolesByUid(user.getId()));
		return user;
	}

}

/////

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

public class User implements UserDetails {
	private Integer id;
	private String username;
	private String password;
	private Boolean enabled;
	private Boolean locked;
	private List<Role> roles;

public User() {}
public User(Integer id, String username, String password, Boolean enabled, Boolean locked, List<Role> roles) {
	super();
	this.id = id;
	this.username = username;
	this.password = password;
	this.enabled = enabled;
	this.locked = locked;
	this.roles = roles;
}



public Integer getId() {
	return id;
}
public void setId(Integer id) {
	this.id = id;
}
public void setEnabled(Boolean enabled) {
	this.enabled = enabled;
}
public Boolean getLocked() {
	return locked;
}
public void setLocked(Boolean locked) {
	this.locked = locked;
}
public List<Role> getRoles() {
	return roles;
}
public void setRoles(List<Role> roles) {
	this.roles = roles;
}

public void setUsername(String username) {
	this.username = username;
}
public void setPassword(String password) {
	this.password = password;
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
	// TODO Auto-generated method stub
	// 配置权限信息
	List<SimpleGrantedAuthority> authorities = new ArrayList<>();
	for (Role role: roles) {
		authorities.add(new SimpleGrantedAuthority(role.getName()));
	}
	return authorities;
}

@Override
public String getPassword() {
	// TODO Auto-generated method stub
	return this.password;
}

@Override
public String getUsername() {
	// TODO Auto-generated method stub
	return this.username;
}

@Override
public boolean isAccountNonExpired() {
	// TODO Auto-generated method stub
	return true;
}

@Override
public boolean isAccountNonLocked() {
	// TODO Auto-generated method stub
	return !locked;
}

@Override
public boolean isCredentialsNonExpired() {
	// TODO Auto-generated method stub
	return true;
}

@Override
public boolean isEnabled() {
	// TODO Auto-generated method stub
	return enabled;
}

}

////

public class Role {
	private Integer id;
	private String name;
	private String nameZh;
	
	public Role () {}

public Role(Integer id, String name, String nameZh) {
	super();
	this.id = id;
	this.name = name;
	this.nameZh = nameZh;
}

public Integer getId() {
	return id;
}

public void setId(Integer id) {
	this.id = id;
}

public String getName() {
	return name;
}

public void setName(String name) {
	this.name = name;
}

public String getNameZh() {
	return nameZh;
}

public void setNameZh(String nameZh) {
	this.nameZh = nameZh;
}
}

///

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class LoginContorller {
	
@RequestMapping("/hello")
public String hello() {
	return "hello world";
}

@RequestMapping("/admin/hello")
public String helloAdmin() {
	return "hello admin";
}

@RequestMapping("/user/hello")
public String helloUser() {
	return "hello user";
}

@RequestMapping("/db/hello")
public String helloDb() {
	return "hello db";
}

@RequestMapping("/login_page")
public String loginPage() {
	return "error";
}
}

That's it! 0.0

Published 20 original articles · won praise 5 · Views 2079

Guess you like

Origin blog.csdn.net/qq_42859887/article/details/103170559