从此
上网
📄文章 #️⃣专题 🌐上网 📺 🛒 📱

Spring Projects


综合

  Spring 6.1 新特性 RestClient 似乎取代了RestTemplate的定位。
  @Component注解的类会作为Bean直接注册到Spring容器,而@Bean注解的方法则是通过方法体手动提供Bean实例。
  子线程取认证:SecurityContextHolder.setStrategyName(SecurityContextHolder.MODE_INHERITABLETHREADLOCAL);
  OAuth Vs SSO单点登录

Spring控制器默认返回html页面名路径,想返回json数据则需要标注@ResponseBody注解!
Spring的JSON库依赖的是Jackson,故首选该库处理JSON相关功能。@Autowired ObjectMapper om;om.writeValueAsString("test");
若想根据if判断返回页面或数据,可通过request.getRequestDispatcher("页面或数据控制器").forward(request, response)中转下!

    @PostMapping("/main/x")
    public String signupAccount() { // 传值用 request.setAttribute("k", "v");
        if (username.startsWith("testtest")) { return "forward:/main/y.json"; }
        return "main/z.html";
    }
    @ResponseBody @PostMapping(value = "/main/y.json",
            produces = MediaType.APPLICATION_JSON_VALUE)
    public String finishJson() { return "{'status':true}"; }

OAuth2基础

Spring Boot

 

Spring Boot 最佳实践

 

vim Hi.java

package com.example;
import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication public class Hi { public static void main(String[] args) { SpringApplication.run(Main.class, args); } }
@RestController class HelloWorld { @RequestMapping("/") public String helloworld() { return "Hello, World!"; } }




build.gradle

 apply plugin: 'java'
...
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-web:2.3.0.RELEASE'
}

 

Run

  gradle -PrunClassName=com.example.Hi runSingle

  访问网址和默认端口 - http://localhost:8080/


Spring Boot 配置 JSP 视图模板引擎 以及和 Thymeleaf 共存

 


 

Spring Security 最佳实践

 

vim Hi.java

package com.example;
import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController;

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;
@SpringBootApplication public class Hi { public static void main(String[] args) { SpringApplication.run(Main.class, args); } }
@RestController class HelloWorld { @RequestMapping("/") public String helloworld() { return "Hello, World!"; } }

// [可选 - 仅用于Spring Security] @EnableWebSecurity class WSCA extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { // http 404 example - http://localhost:8080/new/404 http.authorizeRequests().antMatchers("/new/**").permitAll();

super.configure(http); } }




build.gradle

 apply plugin: 'java'
...
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-web:2.3.0.RELEASE'

// [可选] 启用Form Login表单登录页
// 表单登录默认用户名是user 密码则会输出在控制台 - Using generated security password: 随机生成
implementation 'org.springframework.boot:spring-boot-starter-security:2.3.0.RELEASE'
}




[可选] Spring Security配置文件:
src/main/resources/application.yml

#   更改内置错误页路径 /error 至 /new/error
server:
  error:
    path: /new/error
#   设定默认用户名和密码
spring:
  security:
    user:
      name: user
      password: user



Run
  gradle -PrunClassName=com.example.Hi runSingle

  访问网址和默认端口 - http://localhost:8080/

 


 

Spring CORS跨域:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

@Configuration
public class SpringCORS {

// 用于Spring Security时应提升该Filter优先级:httpSecurity.cors()... @Bean CorsFilter corsFilter() { UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); CorsConfiguration config = new CorsConfiguration(); config.addAllowedOrigin("*"); config.setAllowCredentials(true); config.addAllowedHeader("*"); config.addAllowedMethod("*"); source.registerCorsConfiguration("/**", config); return new CorsFilter(source); } }

 


Spring OAuth2


OAuth 定义了4个角色:
资源拥有者(resource owner) An entity capable of granting access to a protected resource. When the resource owner is a person, it is referred to as an end-user. 资源服务器(resource server) The server hosting the protected resources, capable of accepting and responding to protected resource requests using access tokens. 客户端(client) An application making protected resource requests on behalf of the resource owner and with its authorization. The term "client" does not imply any particular implementation characteristics (e.g., whether the application executes on a server, a desktop, or other devices). 授权服务器(authorization server) The server issuing access tokens to the client after successfully authenticating the resource owner and obtaining authorization.



    OAuth 定义了四种授权模式:

 

 

 

 

  不支持refresh_token

 

    OAuth 提供了两种Token凭据:

 

      Access Token: 用于访问资源服务器

 

      Refresh Token:用于刷新Access Token

 

Spring Authorization Server

数据表oauth2_registered_client字段client_authentication_methods支持列表

client_secret_basic
client_secret_post
client_secret_jwt
private_key_jwt
none (public clients)