添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
  • 如何在CentOS 7上扩展磁盘空间
  • 文档的title,页面及列表都会展示
  • Docker Compose 方式快速启动组件 kafka、Mysql、Redis、 ES、kibana等
  • docker
  • Git 知识汇集
  • 极狐Gitlab Trouble Shooting
  • 在Centos 7.5 上安装 Harbor
  • Java Centos 环境
  • Java 开发工具使用技巧收集
  • jenkins
  • Jenkins 安装
  • kubectl 命令示例
  • macOS 系统使用参考
  • 利用Nexus搭建Maven服务器
  • Maven 知识笔记
  • 基于minikube快读搭建kubernetes集群
  • Nginx 知识点及问题收集
  • 文档的title,页面及列表都会展示
  • odoo 快速开始
  • 构建上海时区JDK镜像
  • Shell 脚本学习笔记
  • Windows 常用命令
  • Centos 常用命令
  • Elastic Technologies
  • Elastcisearch 2.4 Restful API
  • Elasticsearch 2.X 自定义字段的Mapping
  • 文档的title,页面及列表都会展示
  • Elastcisearch 脚本搜集
  • Elasticsearch 模糊匹配
  • Kibana 5.x 加强安全 - x-pack篇
  • 使用ELK来做日志归总
  • Elasticsearch 自定义Mapping
  • ELK docker-compose 监控及日志收集
  • Kong API Gateway 插件开发 - 推送请求日志至Elasticsearch
  • Logstash Filter 配置
  • Metricbeat 的使用
  • kibana的访问控制 - Nginx 反向代理 - 免费
  • 文档的title,页面及列表都会展示
  • Spring Data Elasticsearch 快速上手全文检索 - 进阶
  • Spring Data Elasticsearch 快速上手全文检索
  • English Material
  • 文档的title,页面及列表都会展示
  • It Infrastructures
  • Mac Pro 上 配置 Shadowsocks NG
  • 无线路由器桥接步骤
  • Java Technologies
  • Java编码约定
  • Java并发编程的艺术-01-并发编程的挑战
  • Java并发编程的艺术 -02 Java并发机制的底层实现原理
  • Java JVM
  • Java 正则表达式示例
  • 关于Java 正则表达式的介绍
  • Java 短ID 随机字符串
  • Micro Services
  • Nodejs 使用 JWT和express-http-proxy 来实现简易APIGateway
  • Dubbo + Spring Boot 实现微服务治理
  • Kong Apigateway 快速开始 Docker+DB版
  • Kong API Gateway 插件开发 - 推送请求日志至Elasticsearch
  • Kong 相关资源收集
  • Spring Cloud Netflix 加 Nodejs 技术栈混合搭建微服务
  • Spring Cloud 微服务解决方案
  • Nodejs Technologies
  • 利用sharp来resize 图片
  • Nodejs 利用passport完成本地认证 示例
  • Nodejs 一些积累
  • 向NPM仓库发布自己的Package
  • Centos 7 上利用pm2部署 nodejs 程序 - No Jenkins
  • 使用Raneto结合Github来搭建简易个人的BLog
  • 简易鉴权Api网关
  • Postgresql
  • 文档的title,页面及列表都会展示
  • Private
  • 极狐-Devops 学习笔记
  • Hadoop 3 笔记
  • 软件架构师考试问题
  • mysql 学习
  • Mysql 之事务隔离级别
  • 武汉文旅码二期项目复盘 - 从供应商看总集
  • Software Design
  • 六大设计原则
  • Solutions
  • 有效的基础架构监控的五个好处
  • Kafka 快速开始
  • Redis 命令
  • Spring Boot And Spring Cloud
  • Spring 秘书
  • Spring Boot Actuator
  • Spring Boot Cloud 之配置文件 application vs bootstrap
  • 使用Spring Boot构建多个moudle的web应用
  • Spring Boot开发 web 应用 - 01 创建项目
  • Spring Boot 开发web 应用 - 02 探究竟
  • Spring Boot 开发web 应用 - 03 Spring Framework 回顾
  • Spring Boot 开发web 应用 - 04 静态资源 深入探索
  • Spring Boot 开发web 应用 - 04 静态资源
  • Spring Security 从单体到微服务的演进 - 单体web
  • Spring Boot 1.4 对Unit Test有更好的支持
  • 三步让Spring Boot拥有缓存的能力
  • Spring JPA Data Auditing
  • Spring Kafka 顺序消费问题
  • Spring 路径匹配规则
  • Spring 收集
  • Spring 框架的线程池ThreadPoolTaskExecutor
  • Tricky Part Of Spring Mapping
  • Web Applications Technologies
  • AWS 亚马逊云解决方案 - 动态压缩图片
  • 搞定跨域资源共享 (CORS)
  • Google Analytics 知识点汇总
  • Http Cookie 探索
  • 页面图片懒加载机制
  • Javascript Weird Parts
  • 利用Spring Boot Oauth2 来熟悉oauth2 之 - Authorization Code Grant
  • 对公网站研发的实践经验
  • Restful API 规范
  • Nodejs oauth2 结合 Spring Boot Oauth2 自建 Oauth2 Provider
  • 同源策略下为什么还需要防御CSRF
  • 社交分享在网站中的实现
  • 网站SEO优化最佳实践
  • Work Related
  • 业务中台的演进之路 (文旅项目)
  • 使用Hexo 来建立个人网站
  • PPT 初学笔记
  • 工具资源收集
  • 微信 Wechat相关
  • 个人PPT汇总
  • CSRF - Cross-Site Request Forgery (跨站请求伪造) CORS - Cross Origin Resource Sharing (跨域资源共享)

    单体web app

    创建spring web工程。 采用Spring CLI,(其他多种方式请自便)

    spring init --dependencies web,security ui
    

    OOTB security

    package com.example;
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.http.ResponseEntity;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    @SpringBootApplication
    @RestController
    public class UIApplication {
        public static void main(String[] args) {
            SpringApplication.run(UIApplication.class, args);
        @RequestMapping("/")
        public ResponseEntity<?> home() {
            return ResponseEntity.ok("hello");
    

    OOTB的情况,pom引入了spring security的依赖,不做任何配置。所有的请求都需要登录。

    E:\>curl "http://localhost:8080"
    {"timestamp":1478501120211,"status":401,"error":"Unauthorized","message":"Full authentication is required to access this resource","path":"/"}
    

    从浏览器打开会提示输入用户名和密码,用户名是user,密码可以从console中看到:

    Using default security password: 60fdacf5-347d-4f6f-ac7c-bc0a9725bc55
    

    Look under the hood: 没有任何个性化的配置的时候AuthenticationManagerConfiguration 会采用默认的配置。默认的security配置参考:SecurityProperties类。prefix = "security"。 可通过一下配置修改OOTB的用户名和密码。

    security.user.name=joe
    security.user.password=123456
    

    自定义security

    参考注解: @EnableWebSecurity

    package com.example.security;
    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.builders.WebSecurity;
    import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
    import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
     * @author Joe
    @EnableWebSecurity
    public class ExtWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {
         @Override
         public void configure(WebSecurity web) throws Exception {
             web.ignoring()
             // Spring Security should completely ignore URLs starting with /resources/
                     .antMatchers("/resources/**");
         @Override
         protected void configure(HttpSecurity http) throws Exception {
             http.authorizeRequests()
                     .antMatchers("/public/**").permitAll()
                     .antMatchers("/admin/**").hasRole("ADMIN")
                     .and()
                     // Possibly more configuration ...
                     .formLogin() // enable form based log in
                     // set permitAll for all URLs associated with Form Login
                     .permitAll();
         @Override
         protected void configure(AuthenticationManagerBuilder auth) throws Exception {
             // enable in memory based authentication with a user named "user" and "admin"
             auth.inMemoryAuthentication().withUser("user").password("password").roles("USER")
                     .and().withUser("admin").password("password").roles("USER", "ADMIN");
         // Possibly more overridden methods ...
    

    添加对应URL的接口

    package com.example;
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.http.ResponseEntity;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RestController;
    @SpringBootApplication
    @RestController
    public class UIApplication {
        public static void main(String[] args) {
            SpringApplication.run(UIApplication.class, args);
        @GetMapping("/public/hello")
        public ResponseEntity<?> home() {
            return ResponseEntity.ok("Hello Every one!");
        @GetMapping("/admin/hello")
        public ResponseEntity<?> admin() {
            return ResponseEntity.ok("Hello Admin!");
    

    /public/hello 可以随意访问,/admin/hello 需要登录用户有admin的role。用user登录会抛出403的错误。

    配置中加了.formLogin().permitAll() 未登录用户会直接重定向至OOTB的登录页面。去掉.formLogin().permitAll() 后直接访问/admin/hello会直接抛出403, 而非401 (这点笔者暂时未能理解,未登录应该抛出401 才对,如果系统中加了授权需要区分这两个状态)(什么场景不需要formLogin?用户如何登陆?满足这个场景的web app往往不是单体,可能是某个微服务,提供restful services)。 这里要明白一点:一旦定制,OOTB的行为就会受影响,尽管看似你没有改. 比如:不加.formLogin().permitAll() 就会导致没有登录提示框出现,访问需要授权的服务会直接抛出403

    关于如何配置login的page等参考:Java Configuration and Form Login

    Spring Boot CORS 解决Trick:

    官方示例中只提到了 WebMvcConfigurerAdapter, 然而大部分程序都有WebSecurityConfigurerAdapter 相关的配置

    @Configuration
    @EnableWebSecurity
    public class HrWebSecurityConfig extends WebSecurityConfigurerAdapter {
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.csrf().disable();
            http.cors().and().authorizeRequests().antMatchers("/hr/**").authenticated();
    

    上面代码的:http.cors() 非常重要, 这里java doc拷贝出来

    Adds a CorsFilter to be used. If a bean by the name of corsFilter is provided, that CorsFilter is used. Else if corsConfigurationSource is defined, then that CorsConfiguration is used. Otherwise, if Spring MVC is on the classpath a HandlerMappingIntrospector is used.

    从注解上可以看出来,我们需要一个corsFilter:

    @Bean
        public CorsFilter corsFilter() {
            final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
            final CorsConfiguration config = new CorsConfiguration();
            config.setAllowCredentials(true);
            config.addAllowedOrigin("*");
            config.addAllowedHeader("*");
            config.addAllowedMethod("OPTIONS");
            config.addAllowedMethod("HEAD");
            config.addAllowedMethod("GET");
            config.addAllowedMethod("PUT");
            config.addAllowedMethod("POST");
            config.addAllowedMethod("DELETE");
            config.addAllowedMethod("PATCH");
            source.registerCorsConfiguration("/**", config);
            return new CorsFilter(source);
    

    如果用到了zuul, 上面的配置也不能生效。 stackoverflow 这个issue (zuul 用在apigateway的时候,其他微服务不需要有CORS) Ticket on GitHub