博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
springboot成神之——Basic Auth应用
阅读量:5058 次
发布时间:2019-06-12

本文共 5392 字,大约阅读时间需要 17 分钟。

本文介绍Basic Auth在spring中的应用

目录结构

1108804-20180912085201146-490281621.png

依赖

org.springframework.boot
spring-boot-starter-security

入口DemoApplication

package com.springlearn.learn;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplicationpublic class DemoApplication {    public static void main(String[] args) {        SpringApplication.run(DemoApplication.class, args);    }}

验证Authenication

// 主要是验证不成功返回401package com.springlearn.learn.auth;import java.io.IOException;import java.io.PrintWriter;import javax.servlet.ServletException;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.springframework.security.core.AuthenticationException;import org.springframework.security.web.authentication.www.BasicAuthenticationEntryPoint;import org.springframework.stereotype.Component;@Componentpublic class Authenication extends BasicAuthenticationEntryPoint {    @Override    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authEx)throws IOException, ServletException {        response.addHeader("WWW-Authenticate", "Basic realm=" + getRealmName());        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);        PrintWriter writer = response.getWriter();        writer.println("HTTP Status 401 - " + authEx.getMessage());    }    @Override    public void afterPropertiesSet() throws Exception {\        setRealmName("yejiawei");        super.afterPropertiesSet();    }}

配置WebSecurityConfig

package com.springlearn.learn.config;import javax.sql.DataSource;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;import org.springframework.security.config.annotation.web.builders.HttpSecurity;import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;import org.springframework.security.core.userdetails.User;import org.springframework.security.core.userdetails.UserDetails;import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;import org.springframework.security.web.AuthenticationEntryPoint;import org.springframework.web.servlet.config.annotation.CorsRegistry;import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;import org.springframework.security.config.annotation.authentication.configurers.provisioning.InMemoryUserDetailsManagerConfigurer;@Configuration@EnableWebSecuritypublic class WebSecurityConfig extends WebSecurityConfigurerAdapter implements WebMvcConfigurer{    @Autowired    private AuthenticationEntryPoint authEntryPoint;    @Autowired    DataSource dataSource;    @Override    protected void configure(HttpSecurity http) throws Exception {        http.cors().and().csrf().disable();        // 所有的请求都要验证        http.authorizeRequests().anyRequest().authenticated();        // 使用authenticationEntryPoint验证 user/password        http.httpBasic().authenticationEntryPoint(authEntryPoint);    }    @Bean    public BCryptPasswordEncoder passwordEncoder() {        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();        return bCryptPasswordEncoder;    }    @Autowired    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {        String password = "234";        String encrytedPassword = this.passwordEncoder().encode(password);        System.out.println("Encoded password = " + encrytedPassword);        // 这里使用写死的验证,你可以在这里访问数据库        InMemoryUserDetailsManagerConfigurer
mngConfig = auth.inMemoryAuthentication(); UserDetails u1 = User.withUsername("yejiawei").password(encrytedPassword).roles("ADMIN").build(); UserDetails u2 = User.withUsername("donglei").password(encrytedPassword).roles("USER").build(); mngConfig.withUser(u1); mngConfig.withUser(u2); } @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**").allowedOrigins("*").allowedMethods("GET", "POST", "PUT", "DELETE").allowedOrigins("*") .allowedHeaders("*"); }}

控制器TestController

package com.springlearn.learn.controller;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.springframework.security.core.Authentication;import org.springframework.security.core.context.SecurityContextHolder;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import org.springframework.web.bind.annotation.ResponseBody;import org.springframework.web.bind.annotation.RestController;@RestControllerpublic class TestController {    @ResponseBody    @RequestMapping(value = "/AuthTest", method = RequestMethod.GET)    public String AuthTest(HttpServletRequest request, HttpServletResponse response) {        Authentication auth = SecurityContextHolder.getContext().getAuthentication();        System.out.println(auth.getName());        return "OK";    }}

前端访问

    
Document

转载于:https://www.cnblogs.com/ye-hcj/p/9632694.html

你可能感兴趣的文章
poi操作oracle数据库导出excel文件
查看>>
(转)Intent的基本使用方法总结
查看>>
《梦断代码》读书笔记(三)
查看>>
FreeMarker解析json数据
查看>>
Java8 Lambda表达应用 -- 单线程游戏server+异步数据库操作
查看>>
[Unity3D]Unity3D游戏开发MatchTarget的作用攀登效果实现
查看>>
AngularJS学习篇(一)
查看>>
关于Xshell无法连接centos6.4的问题
查看>>
css3动画——基本准则
查看>>
javaweb常识
查看>>
Java注解
查看>>
web自己主动保存表单
查看>>
一个小的日常实践——高速Fibonacci数算法
查看>>
机器学些技法(9)--Decision Tree
查看>>
drf权限组件
查看>>
输入月份和日期,得出是今年第几天
查看>>
【linux】重置fedora root密码
查看>>
pig自定义UDF
查看>>
Kubernetes 运维学习笔记
查看>>
spring security 11种过滤器介绍
查看>>