0% found this document useful (0 votes)
19 views52 pages

07 Security1

The document discusses the architecture of enterprise applications with a focus on security, specifically using Spring Security for authentication and authorization. It covers various topics such as digital signatures, code signing, encryption, and provides code samples for implementing security features in applications. Additionally, it explains the importance of message digests and X.509 certificates in ensuring data integrity and secure communication.

Uploaded by

shenkuncst
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views52 pages

07 Security1

The document discusses the architecture of enterprise applications with a focus on security, specifically using Spring Security for authentication and authorization. It covers various topics such as digital signatures, code signing, encryption, and provides code samples for implementing security features in applications. Additionally, it explains the importance of message digests and X.509 certificates in ensuring data integrity and secure communication.

Uploaded by

shenkuncst
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 52

Architecture of Enterprise Applications 07

Security

Haopeng Chen

REliable, INtelligent and Scalable Systems Group (REINS)


Shanghai Jiao Tong University
Shanghai, China
http://reins.se.sjtu.edu.cn/~chenhp
e-mail: [email protected]
Contents and Objectives REliable, INtelligent & Scalable Systems

• Contents
– Spring Security Samples
– SECURITY
• DIGITAL SIGNATURES
• CODE SIGNING
• ENCRYPTION

• Objectives
– 能够根据业务需求,配置使用合理的加密通信方式,并能够理解其基本原理与工作方式
Spring Security REliable, INtelligent & Scalable Systems

• Spring Security
– provides comprehensive support for authentication, authorization, and protection against common
exploits. It also provides integration with other libraries to simplify its usage.
– https://docs.spring.io/spring-security/site/docs/current/reference/html5/#features

3
Spring Security - Login Sample REliable, INtelligent & Scalable Systems

• MvcConfig.java

@Configuration
public class MvcConfig implements WebMvcConfigurer {

public void addViewControllers(ViewControllerRegistry registry) {


registry.addViewController("/home").setViewName("home");
registry.addViewController("/").setViewName("home");
registry.addViewController("/hello").setViewName("hello");
registry.addViewController("/login").setViewName("login");
}

4
Login Sample REliable, INtelligent & Scalable Systems

• WebSecurityConfigureAdapter.java
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/", "/home").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.permitAll();
}

5
Spring Security - Login Sample REliable, INtelligent & Scalable Systems

• WebSecurityConfigureAdapter.java
@Bean
@Override
public UserDetailsService userDetailsService() {
UserDetails user =
User.withDefaultPasswordEncoder()
.username("user")
.password("password")
.roles("USER")
.build();

return new InMemoryUserDetailsManager(user);


}
}

6
Spring Security - Login Sample REliable, INtelligent & Scalable Systems

• home.html

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="https://www.thymeleaf.org"
xmlns:sec="https://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
<title>Spring Security Example</title>
</head>
<body>
<h1>Welcome!</h1>

<p>Click <a th:href="@{/hello}">here</a> to see a greeting.</p>


</body>
</html>

7
Login Sample REliable, INtelligent & Scalable Systems

• hello.html

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="https://www.thymeleaf.org"
xmlns:sec="https://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
<title>Hello World!</title>
</head>
<body>
<h1 th:inline="text">Hello [[${#httpServletRequest.remoteUser}]]!</h1>
<form th:action="@{/logout}" method="post">
<input type="submit" value="Sign Out"/>
</form>
</body>
</html>

8
Login Sample REliable, INtelligent & Scalable Systems

• login.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="https://www.thymeleaf.org"
xmlns:sec="https://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
<title>Spring Security Example </title>
</head>
<body>
<div th:if="${param.error}">
Invalid username and password.
</div>
<div th:if="${param.logout}">
You have been logged out.
</div>
<form th:action="@{/login}" method="post">
<div><label> User Name : <input type="text" name="username"/> </label></div>
<div><label> Password: <input type="password" name="password"/> </label></div>
<div><input type="submit" value="Sign In"/></div>
</form>
</body>
</html>
9
Login Sample REliable, INtelligent & Scalable Systems

10
React + Spring Security: Front-end REliable, INtelligent & Scalable Systems

• App.js import React from 'react';


import {BrowserRouter as Router, Switch, Route, Link} from "react-router-dom";
import Info from './component/Info';
function App() {
return (
<Router>
<div>
<nav>
<ul>
<li><Link to="/">Home</Link></li>
<li><Link to="/about">About</Link></li>
<li><Link to="/users">Users</Link></li>
</ul>
</nav>
<Switch>
<Route path="/about"><Info menu="about"/></Route>
<Route path="/users"><Info menu="users"/></Route>
<Route path="/"><Info menu=""/></Route>
</Switch>
</div>
</Router>
);
}
export default App;

11
React + Spring Security: Front-end REliable, INtelligent & Scalable Systems

• Info.js import React from 'react';


function Info(props) {
let url = 'http://localhost:8080/' + props.menu;
let username = 'root';
let password = '123';
let headers = new Headers();
headers.set('Authorization', 'Basic ' + Buffer.from(username + ":" + password).toString('base64'));

fetch(url, {
method: 'GET',
headers: headers,
credentials: 'include'
}).then(response => response.text())
.then(data => {
document.getElementById("info").innerText = data
}).catch(function (ex) {
console.log('parsing failed', ex)
})
return (
<div>
<h1 id="info">Welcome</h1>
</div>
);
}
export default Info;

12
React + Spring Security: Back-end REliable, INtelligent & Scalable Systems

• SpringSecurityApplication.java
@SpringBootApplication(exclude= {DataSourceAutoConfiguration.class})
public class SpringSecurityApplication {
public static void main(String[] args) {
SpringApplication.run(SpringSecurityApplication.class, args);
}
}

• application.properties

spring.security.user.name=root
spring.security.user.password=123

13
React + Spring Security: Back-end REliable, INtelligent & Scalable Systems

• GreetingController.java
@CrossOrigin(maxAge = 3600)
@RestController
public class GreetingController {
@GetMapping("/about")
public String getAbout() {
return "This is a Spring security sample";
}

@GetMapping("/users")
public String getUser() {
return "I am a user";
}

@GetMapping("/")
public String getHome() {
return "Let' start!";
}
}
14
React + Spring Security: Back-end REliable, INtelligent & Scalable Systems

@Configuration
• SecurityConfig.java public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors()
.and()
.authorizeRequests(authorize -> authorize
.antMatchers(“/”).permitAll()
.antMatchers(“/users”,“/about”).authenticated()
)
.httpBasic(withDefaults())
}
@Bean
public CorsConfigurationSource corsConfigurationSource() {
final CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(ImmutableList.of("*"));
configuration.setAllowedMethods(ImmutableList.of("HEAD", "GET", "POST", "PUT", "DELETE", "PATCH"));
configuration.setAllowCredentials(true);
configuration.setAllowedHeaders(ImmutableList.of("Authorization", "Cache-Control", "Content-Type"));
final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
} 15
React + Spring Security: Back-end REliable, INtelligent & Scalable Systems

• CorsConfig.java
@Configuration
public class CorsConfig implements WebMvcConfigurer {

@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowedMethods("*")
.allowedHeaders("*")
.exposedHeaders(HttpHeaders.SET_COOKIE)
.allowCredentials(true).maxAge(1800);
}
}

16
Run the application REliable, INtelligent & Scalable Systems

17
Digital Signatures REliable, INtelligent & Scalable Systems

• To give more trust to an applet, we need to know two things:


– Where did the applet come from?
– Was the code corrupted in transit?

18
Message Digests REliable, INtelligent & Scalable Systems

• A message digest is a digital fingerprint of a block of data.


– For example, the so-called SHA1 (secure hash algorithm #1) condenses any data
block, no matter how long, into a sequence of 160 bits (20 bytes).

• A message digest has two essential properties:


– If one bit or several bits of the data are changed, then the message digest also
changes.
– A forger who is in possession of a given message cannot construct a fake message
that has the same message digest as the original.

19
Message Digests REliable, INtelligent & Scalable Systems

• Consider the following message by the billionaire father:


– "Upon my death, my property shall be divided equally among my children;
however, my son George shall receive nothing."
– That message has an SHA1 fingerprint of
• 2D 8B 35 F3 BF 49 CD B1 94 04 E0 66 21 2B 5E 57 70 49 E1 7E
– Now, suppose George wants to change the message so that Bill gets nothing. That
changes the fingerprint to a completely different bit pattern:
• 2A 33 0B 4B B3 FE CC 1C 9D 5C 01 A7 09 51 0B 49 AC 8F 98 92

20
Message Digests REliable, INtelligent & Scalable Systems

MessageDigest alg = MessageDigest.getInstance("SHA-1");

InputStream in = . . .
int ch;
while ((ch = in.read( )) != -1)
alg.update((byte) ch);

byte[ ] bytes = . . .;
alg.update(bytes);

byte[ ] hash = alg.digest( );

21
Message Signing REliable, INtelligent & Scalable Systems

• The message digest algorithms are publicly known, and they


don't require secret keys.
– In that case, the recipient of the forged message and the recomputed fingerprint
would never know that the message has been altered.
– Digital signatures solve this problem.

22
Message Signing REliable, INtelligent & Scalable Systems

• The keys are quite long and complex. For example, here is a matching pair of public and
private Digital Signature Algorithm (DSA) keys.
• Public key:
• Code View:
– p: fca682ce8e12caba26efccf7110e526db078b05edecbcd1eb4a208f3ae1617ae01f35b91a47e6df63413c5e12ed0899
bcd132acd50d99151bdc43ee737592e17 q: 962eddcc369cba8ebb260ee6b6a126d9346e38c5
g:678471b27a9cf44ee91a49c5147db1a9aaf244f05a434d6486931d2d14271b9e35030b71fd73da179069b32e29356 30e
1c2062354d0da20a6c416e50be794ca4 y:
c0b6e67b4ac098eb1a32c5f8c4c1f0e7e6fb9d832532e27d0bdab9ca2d2a8123ce5a8018b8161a760480fadd040b927
281ddb22cb9bc4df596d7de4d1b977d50

• Private key:
• Code View:
– p: fca682ce8e12caba26efccf7110e526db078b05edecbcd1eb4a208f3ae1617ae01f35b91a47e6df63413c5e12ed0899
bcd132acd50d99151bdc43ee737592e17 q: 962eddcc369cba8ebb260ee6b6a126d9346e38c5 g:
678471b27a9cf44ee91a49c5147db1a9aaf244f05a434d6486931d2d14271b9e35030b71fd73da179069b32e2935630
e1c2062354d0da20a6c416e50be794ca4 x: 146c09f881656cc6c51f27ea6c3a91b85ed1d70a

23
Message Signing REliable, INtelligent & Scalable Systems

24
X.509 Certificate REliable, INtelligent & Scalable Systems

• To take advantage of public key cryptography, the public keys must be


distributed.
– One of the most common distribution formats is called X.509.

• The keytool program manages keystores, databases of certificates and


private/public key pairs.
– Each entry in the keystore has an alias.
– Here is how Alice creates a keystore, alice.certs, and generates a key pair with alias alice.
– keytool -genkeypair -keystore alice.certs -alias alice

25
X.509 Certificate REliable, INtelligent & Scalable Systems

• When generating a key, you are prompted for the following information:
Enter keystore password: password
What is your first and last name?
[Unknown]: Alice Lee
What is the name of your organizational unit?
[Unknown]: Engineering Department
What is the name of your organization?
[Unknown]: ACME Software
What is the name of your City or Locality?
[Unknown]: Cupertino
What is the name of your State or Province?
[Unknown]: California
What is the two-letter country code for this unit?
[Unknown]: US
Is <CN=Alice Lee, OU=Engineering Department, O=ACME Software, L=Cupertino, ST=California,
C=US> correct?
[no]: Y
26
X.509 Certificate REliable, INtelligent & Scalable Systems

• Alice exports a certificate file:


– keytool -exportcert -keystore alice.certs -alias alice -file alice.cer

• Bob receives the certificate, he can print it:


– keytool -printcert -file alice.cer

• The printout looks like this:


Owner: CN=Alice Lee, OU=Engineering Department, O=ACME Software,
L=San Francisco, ST=CA, C=US
Issuer: CN=Alice Lee, OU=Engineering Department, O=ACME Software,
L=San Francisco, ST=CA, C=US
Serial number: 470835ce
Valid from: Sat Oct 06 18:26:38 PDT 2007 until: Fri Jan 04 17:26:38 PST 2008
Certificate fingerprints:
MD5: BC:18:15:27:85:69:48:B1:5A:C3:0B:1C:C6:11:B7:81
SHA1: 31:0A:A0:B8:C2:8B:3B:B6:85:7C:EF:C0:57:E5:94:95:61:47:6D:34
Signature algorithm name: SHA1withDSA
Version: 3 27
X.509 Certificate REliable, INtelligent & Scalable Systems

• Once Bob trusts the certificate, he can import it into his keystore.
– keytool -importcert -keystore bob.certs -alias alice -file alice.cer
• Now Alice can start sending signed documents to Bob.
– jar cvf document.jar document.txt
– jarsigner -keystore alice.certs document.jar alice
• When Bob receives the file, he uses the -verify option of the jarsigner program.
– jarsigner -verify -keystore bob.certs document.jar
• If the JAR file is not corrupted and the signature matches, then the jarsigner program
prints
– jar verified.
– Otherwise, the program displays an error message.

28
Authentication Problem REliable, INtelligent & Scalable Systems

• Be careful:
– You still have no idea who wrote the message. Anyone could have generated a pair of public
and private keys, signed the message with the private key, and sent the signed message and
the public key to you.
– The problem of determining the identity of the sender is called the authentication problem.

29
Authentication Problem REliable, INtelligent & Scalable Systems

30
Certificate Signing REliable, INtelligent & Scalable Systems

• Suppose Alice wants to send her colleague Cindy a signed message


– but Cindy doesn't want to bother with verifying lots of signature fingerprints.
– Now suppose that there is an entity that Cindy trusts to verify signatures. In this example,
Cindy trusts the Information Resources Department at ACME Software.
• That department operates a certificate authority (CA).
– Everyone at ACME has the CA's public key in their keystore, installed by a system
administrator who carefully checked the key fingerprint.
– The CA signs the keys of ACME employees.
– When they install each other's keys, then the keystore will trust them implicitly because they
are signed by a trusted key.

31
Certificate Signing REliable, INtelligent & Scalable Systems

• Here is how you can simulate this process.


– Create a keystore acmesoft.certs.
– Generate a key par and export the public key:
• keytool -genkeypair -keystore acmesoft.certs -alias acmeroot
• keytool -exportcert -keystore acmesoft.certs -alias acmeroot -file acmeroot.cer
– The public key is exported into a "self-signed" certificate.
– Then add it to every employee's keystore.
• keytool -importcert -keystore cindy.certs -alias acmeroot -file acmeroot.cer
– An authorized staff member at ACME Software would verify Alice's identity and generate
a signed certificate as follows:
• java CertificateSigner -keystore acmesoft.certs -alias acmeroot -infile alice.cer -outfile
alice_signedby_acmeroot.cer
– Now Cindy imports the signed certificate into her keystore:
• keytool -importcert -keystore cindy.certs -alias alice -file alice_signedby_acmeroot.cer
32
Code Signing REliable, INtelligent & Scalable Systems

• One of the most important uses of authentication technology is


signing executable programs.

• You now know how to implement this sophisticated scheme.


– Use authentication to verify where the code came from.
– Run the code with a security policy that enforces the permissions that you want to
grant the program, depending on its origin.

33
JAR File Signing REliable, INtelligent & Scalable Systems

• ACME decides to sign the JAR files that contain the program code.
– First, ACME generates a root certificate:
• keytool -genkeypair -keystore acmesoft.certs -alias acmeroot
– Therefore, we create a second keystore client.certs for the public certificates and add the
public acmeroot certificate into it.
• keytool -exportcert -keystore acmesoft.certs -alias acmeroot -file acmeroot.cer
• keytool -importcert -keystore client.certs -alias acmeroot -file acmeroot.cer
– To make a signed JAR file, programmers add their class files to a JAR file in the usual way. For
example,
• javac FileReadApplet.java
• jar cvf FileReadApplet.jar *.class
– Then a trusted person at ACME runs the jarsigner tool, specifying the JAR file and the alias of
the private key:
• jarsigner -keystore acmesoft.certs FileReadApplet.jar acmeroot

34
JAR File Signing REliable, INtelligent & Scalable Systems

• ACME decides to sign the JAR files.


– Next, let us turn to the client machine configuration. A policy file must be distributed to each
client machine.
– To reference a keystore, a policy file starts with the line
• keystore "keystoreURL", "keystoreType";
– The URL can be absolute or relative.
• keystore "client.certs", "JKS";
– Then grant clauses can have suffixes signedBy "alias", such as this one:
• grant signedBy "acmeroot" { . . . };
– Now create a policy file applet.policy with the contents:
• keystore "client.certs", "JKS";
• grant signedBy "acmeroot" {
• permission java.lang.RuntimePermission "usePolicy";
• permission java.io.FilePermission "/etc/*", "read";
• };
35
Software Developer Certificates REliable, INtelligent & Scalable Systems

• A program signed with a software developer certificate that is issued by a CA


will trigger a pop-up dialog box identifies the software developer and the
certificate issuer.
– You now have two choices:
• Run the program with full privileges.
• Confine the program to the sandbox. (The Cancel button in the dialog box is misleading. If you click
that button, the applet is not canceled. Instead, it runs in the sandbox.)

36
Symmetric Ciphers REliable, INtelligent & Scalable Systems

• Cipher
Cipher cipher = Cipher.getInstance(algorithName);
– or
Cipher cipher = Cipher.getInstance(algorithName, providerName);
– The JDK comes with ciphers by the provider named "SunJCE".
– The algorithm name is a string such as "AES" or "DES/CBC/PKCS5Padding".

int mode = . . .; Key key = . . .; cipher.init(mode, key);


– The mode is one of
Cipher.ENCRYPT_MODE
Cipher.DECRYPT_MODE
Cipher.WRAP_MODE
Cipher.UNWRAP_MODE

37
Symmetric Ciphers REliable, INtelligent & Scalable Systems

int blockSize = cipher.getBlockSize();


byte[] inBytes = new byte[blockSize];
. . . // read inBytes
int outputSize= cipher.getOutputSize(inLength);
byte[] outBytes = new byte[outputSize];
int outLength = cipher.update(inBytes, 0, outputSize, outBytes);
. . . // write outBytes

outBytes = cipher.doFinal(inBytes, 0, inLength);


– Or
outBytes = cipher.doFinal();
– The call to doFinal is necessary to carry out padding of the final block.
L 01 if length(L) = 7
L 02 02 if length(L) = 6
L 03 03 03 if length(L) = 5
...
L 07 07 07 07 07 07 07 if length(L) = 1
08 08 08 08 08 08 08 08
38
Key generation REliable, INtelligent & Scalable Systems

• Follow these steps:


– Get a KeyGenerator for your algorithm.
– Initialize the generator with a source for randomness. If the block length of the cipher is variable,
also specify the desired block length.
– Call the generateKey method.
KeyGenerator keygen = KeyGenerator.getInstance("AES");
SecureRandom random = new SecureRandom();
keygen.init(random);
Key key = keygen.generateKey();
Or
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("AES");
byte[] keyData = . . .; // 16 bytes for AES
SecretKeySpec keySpec = new SecretKeySpec(keyData, "AES");
Key key = keyFactory.generateSecret(keySpec);

39
Cipher Streams REliable, INtelligent & Scalable Systems

• The JCE library provides a convenient set of stream classes that automatically encrypt
or decrypt stream data.
• Encryption
Cipher cipher = . . .;
cipher.init(Cipher.ENCRYPT_MODE, key);
CipherOutputStream out = new CipherOutputStream(new FileOutputStream(outputFileName),
cipher);
byte[] bytes = new byte[BLOCKSIZE];
int inLength = getData(bytes); // get data from data source
while (inLength != -1) {
out.write(bytes, 0, inLength);
inLength = getData(bytes); // get more data from data source
} out.flush();

40
Cipher Streams REliable, INtelligent & Scalable Systems

• The JCE library provides a convenient set of stream classes that automatically encrypt
or decrypt stream data.
• Decryption
Cipher cipher = . . .;
cipher.init(Cipher.DECRYPT_MODE, key);
CipherInputStream in = new CipherInputStream(new FileInputStream(inputFileName), cipher);
byte[] bytes = new byte[BLOCKSIZE];
int inLength = in.read(bytes);
while (inLength != -1) {
putData(bytes, inLength); // put data to destination
inLength = in.read(bytes);
}

41
Public Key Ciphers REliable, INtelligent & Scalable Systems

• The Achilles heel of symmetric ciphers is key distribution.


– Public key cryptography solves that problem.
• All known public key algorithms are much slower than symmetric key algorithms
such as DES or AES.
– It would not be practical to use a public key algorithm to encrypt large amounts of information.
• This problem can easily be overcome by combining a public key cipher with a fast
symmetric cipher, like this:
– Alice generates a random symmetric encryption key. She uses it to encrypt her plaintext.
– Alice encrypts the symmetric key with Bob's public key.
– Alice sends Bob both the encrypted symmetric key and the encrypted plaintext.
– Bob uses his private key to decrypt the symmetric key.
– Bob uses the decrypted symmetric key to decrypt the message.

42
Introduction to SSL/TLS REliable, INtelligent & Scalable Systems

• Transport Layer Security (TLS) and its predecessor, Secure Sockets Layer (SSL),
– are technologies which allow web browsers and web servers to communicate over a secured
connection.
– This means that the data being sent is encrypted by one side, transmitted, then decrypted by the
other side before processing.
– This is a two-way process, meaning that both the server AND the browser encrypt all traffic before
sending out data.
• Another important aspect of the SSL/TLS protocol is Authentication.
– This means that during your initial attempt to communicate with a web server over a secure
connection, that server will present your web browser with a set of credentials, in the form of a
"Certificate", as proof the site is who and what it claims to be.
– In certain cases, the server may also request a Certificate from your web browser, asking for proof
that you are who you claim to be.
– This is known as "Client Authentication", although in practice this is used more for business-to-
business (B2B) transactions than with individual users. Most SSL-enabled web servers do not request
Client Authentication.
43
SSL in Tomcat REliable, INtelligent & Scalable Systems

• https://blog.csdn.net/qq_42549122/article/details/90272299

44
Configuration in Tomcat REliable, INtelligent & Scalable Systems

• Create a keystore file to store the server's private key and self-signed certificate by
executing the following command:
– Windows:
– “%JAVA_HOME%\bin\keytool” -genkey -alias tomcat -keyalg RSA -keystore “C:\Tomcat\conf\key\
tomcat.keystore” -validity 365

– Unix:
– $JAVA_HOME/bin/keytool -genkey -alias tomcat -keyalg RSA -keystore ./conf/key/tomcat.keystore
-validity 365

45
Configuration in Tomcat REliable, INtelligent & Scalable Systems

• For External Tomcat -> Edit the Tomcat Configuration File ./conf/server.xml
<Connector port=“8443”
protocol="org.apache.coyote.http11.Http11NioProtocol"
maxThreads="150" SSLEnabled="true"
keystoreFile="/Users/chenhaopeng/apache-tomcat-9.0.31/conf/key/tomcat.keystore"
keystorePass="changeit">
</Connector>

• For Spring nested Tomcat -> Edit application.properties


server.port=8443
server.ssl.key-store=/Users/chenhaopeng/apache-tomcat-9.0.31/conf/key/tomcat.keystore
server.ssl.key-store-password=changeit
server.ssl.keyAlias=tomcat

46
Test SSL in Tomcat REliable, INtelligent & Scalable Systems

• Spring-boot Project
@SpringBootApplication
public class DemoApplication {

@Bean
public TomcatServletWebServerFactory tomcatServletWebServerFactory(Connector connector){
TomcatServletWebServerFactory tomcat=new TomcatServletWebServerFactory(){
@Override
protected void postProcessContext(Context context) {
SecurityConstraint securityConstraint=new SecurityConstraint();
securityConstraint.setUserConstraint("CONFIDENTIAL");
SecurityCollection collection=new SecurityCollection();
collection.addPattern("/*");
securityConstraint.addCollection(collection);
context.addConstraint(securityConstraint);
}
};
tomcat.addAdditionalTomcatConnectors(connector);
return tomcat;
}

47
Test SSL in Tomcat REliable, INtelligent & Scalable Systems

• Spring-boot Project
@SpringBootApplication
public class DemoApplication {

@Bean
public Connector connector(){
Connector connector=new Connector("org.apache.coyote.http11.Http11NioProtocol");
connector.setScheme("http");
connector.setPort(8080);
connector.setSecure(false);
connector.setRedirectPort(8443);
return connector;
}

public static void main(String[] args) {


SpringApplication.run(DemoApplication.class, args);
}

48
Test SSL in Tomcat REliable, INtelligent & Scalable Systems

• MsgController.java

@RestController
public class MsgController {
@Autowired
WebApplicationContext applicationContext;

@GetMapping(value = "/msg")
public String findOne( ) {
System.out.println("Sending an email message.");
return "Hello World!";
};
}

49
Test SSL in Tomcat REliable, INtelligent & Scalable Systems

• MsgController.java

@RestController
public class MsgController {
@Autowired
WebApplicationContext applicationContext;

@GetMapping(value = "/msg")
public String findOne( ) {
System.out.println("Sending an email message.");
return "Hello World!";
};
}

50
References REliable, INtelligent & Scalable Systems

• Core Java (volume II) 11th edition


– http://horstmann.com/corejava.html
• The Java EE 7 Tutorial
– http://docs.oracle.com/javaee/7/tutorial/doc/javaeetutorial7.pdf
• Software Architecture in Practice, Second Edition
– By Len Bass, Paul Clements, Rick Kazman
– Publisher : Addison Wesley
• 如何在 Spring 启动时在 Spring Security 级别启用 CORS(How to enable CORS at Spring Security level in Spring boot)
– http://www.it1352.com/978249.html
• Securing a Web Application
– https://spring.io/guides/gs/securing-web/
• SSL/TLS Configuration How-To
– https://tomcat.apache.org/tomcat-10.0-doc/ssl-howto.html - Configuration
• spring boot 进行开启 SSL 安全验证( application.properties 不能配置两个端口)
– https://blog.csdn.net/lan12334321234/article/details/84912188
• Springboot 配置 ssl 证书踩坑记
– https://blog.csdn.net/qq_16410733/article/details/89518650
• Tomcat8.5 配置 https 和 SpringBoot 配置 https
– https://blog.csdn.net/wangxudongx/article/details/89534071
51
Thank You!

You might also like