SpringSecurity之学习路途
2021-03-08 05:28
标签:输入 direct ide date type lis 查询 json格式 disable 项目:Github 在manven依赖仓库中:
1.在包下创建SecurityCconfig类,重写configure方法,其中WebSecurity web,可以定义忽略路径 简单的表单登录配置,这里的logou是Get请求,若要Post请求,则增加一行 and相当于ssm中标签的结束,permitAll表示登录相关的页面、操作不要拦截。
实体,加注解 创建Dao 在测试类中: 这样在用dao层去注入实体,在数据库中,也会生成表格,数据。如下: 是有点自恋,啊。原谅想帅的小胖子。
在此方法中,从数据库中根据username,查询出用户,角色,返回UserDetail对象。 到此,我们的表单登录,就成功了。通过doLogin登录,携带user信息,进入
在这里说下, 测试登录 SpringSecurity之学习路途 标签:输入 direct ide date type lis 查询 json格式 disable 原文地址:https://www.cnblogs.com/Choleen/p/14209202.htmlSpring Security 学习之旅开端
SpringSecurity 开始
1. 引入依赖
2. 配置Security
@Override
public void configure(WebSecurity web) throws Exception {
//忽略拦截
web.ignoring().antMatchers("/sayHello","/doLogin");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()//开启登录
//表示访问,ex/index 这个接口,需要具备admin角色
.antMatchers("/es/**").hasRole("admin")
//表示剩余的其他接口,登录之后能访问
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
//登录处理接口
.loginProcessingUrl("/doLogin")
//定义登录时,用户名的key,默认为username
.usernameParameter("username")
//定义登录时,用户密码的key,默认为password
.passwordParameter("password")
//定义登录成功的处理器
.successHandler(new AuthenticationSuccessHandler() {
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
response.setContentType("application/json;charset=utf-8");
response.sendRedirect("/success.html");//重定向到一个页面
MyUserDetails detail= (MyUserDetails)authentication.getPrincipal();
System.out.println(detail);
}
})
.failureHandler(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();
ResponseBean responseBean = ResponseBean.sendByCode("you have login failure !", 401);
String result = new ObjectMapper().writeValueAsString(responseBean);
out.write(result);
out.flush();
}
})
//和表单登录相关的接口统统都直接通过
.permitAll()
.and()
.logout()
.logoutUrl("/logout")
.logoutSuccessHandler(new LogoutSuccessHandler() {
@Override
public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
response.setContentType("application/json;charset=utf-8");
PrintWriter out = response.getWriter();
out.write("you have login out success !");
out.flush();
}
})
.permitAll()
.and()
.httpBasic()
.and()
.csrf().disable();
}
logoutRequestMatcher(new AntPathRequestMatcher("/logout","POST"))
由于security自带盐,用明文加密的都不一样,省去了我们很多时间。 @Bean
public PasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
@Data
@Entity(name = "t_user")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String username;
private String password;
private Integer enabled;
private Integer locked;
}
@Data
@Entity(name = "t_role")
public class Role {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String name;
private String chineseName;
}
@Data
public class MyUserDetails implements UserDetails {
private User user;
private List
在测试类中,创建对象,jpa会自动去创建表格。做一个示范,由于学习,我先创建的表格,你们可以少走弯路了。比如下面这样:@Data
@Entity(name = "t_hill_heavy")
public class HillHeavy {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String username;
private Boolean handsome;
private String gender;
private Integer high;
private boolean rich;
public interface HillHeavyDao extends JpaRepository
@SpringBootTest
class EsSearchApplicationTests {
private static final Logger logger = LoggerFactory.getLogger(EsSearchApplicationTests.class);
@Resource
private HillHeavyDao hillHeavyDao;
@Test
void contextLoads() {
HillHeavy hillHeavy = new HillHeavy();
hillHeavy.setUsername("山沉");
hillHeavy.setHandsome(true);
hillHeavy.setHigh(180);
hillHeavy.setGender("男");
hillHeavy.setRich(true);
hillHeavyDao.save(hillHeavy);
logger.info("实体----->{}",hillHeavy);
}
}
loadUserByUserName(String username)
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = userMapper.selectUser(username);
MyUserDetails details = new MyUserDetails();
if(user == null){
throw new BadCredentialsException("this username or password is not true!");
}
details.setUser(user);
Integer id = user.getId();
List
3. 测试登录
UsernamePasswordAuthenticationFilter
中,注入用户信息。在从表中获得用户信息与之对比,然后通过登录成功或失败返回给前端JSON格式。successHandler
是比较强大的,在里面可以作重定向,也可以获取用户信息,等等。集成 defaultSuccessUrl() successForwardUrl()
。
defaultSuccessUrl
可以指定登录成功的跳转页面,比如输入 welcome/say
,来到login.html
页面。登录成功后,会来的welcome/say
。sccessForwardUrl
指定登录成功后,到那里。不管登录前你操作的哪一个接口,成功后一律到指定的路径。
文章标题:SpringSecurity之学习路途
文章链接:http://soscw.com/index.php/essay/61669.html